Merge pull request #909 from tvaneerd/patch-2
[CppCoreGuidelines.git] / CppCoreGuidelines.md
blob3648fa2d9487d03e26a23fd2d35fe228a6bc1eeb
1 # <a name="main"></a>C++ Core Guidelines
3 April 30, 2017
6 Editors:
8 * [Bjarne Stroustrup](http://www.stroustrup.com)
9 * [Herb Sutter](http://herbsutter.com/)
11 This document is a very early draft. It is inkorrekt, incompleat, and pµÃoorly formatted.
12 Had it been an open source (code) project, this would have been release 0.7.
13 Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
14 Contributing to this project requires agreeing to a Contributor License. See the accompanying [LICENSE](LICENSE) file for details.
15 We make this project available to "friendly users" to use, copy, modify, and derive from, hoping for constructive input.
17 Comments and suggestions for improvements are most welcome.
18 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
19 When commenting, please note [the introduction](#S-introduction) that outlines our aims and general approach.
20 The list of contributors is [here](#SS-ack).
22 Problems:
24 * The sets of rules have not been thoroughly checked for completeness, consistency, or enforceability.
25 * Triple question marks (???) mark known missing information
26 * Update reference sections; many pre-C++11 sources are too old.
27 * For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified)
29 You can [read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
31 * [In: Introduction](#S-introduction)
32 * [P: Philosophy](#S-philosophy)
33 * [I: Interfaces](#S-interfaces)
34 * [F: Functions](#S-functions)
35 * [C: Classes and class hierarchies](#S-class)
36 * [Enum: Enumerations](#S-enum)
37 * [R: Resource management](#S-resource)
38 * [ES: Expressions and statements](#S-expr)
39 * [Per: Performance](#S-performance)
40 * [CP: Concurrency](#S-concurrency)
41 * [E: Error handling](#S-errors)
42 * [Con: Constants and immutability](#S-const)
43 * [T: Templates and generic programming](#S-templates)
44 * [CPL: C-style programming](#S-cpl)
45 * [SF: Source files](#S-source)
46 * [SL: The Standard library](#S-stdlib)
48 Supporting sections:
50 * [A: Architectural Ideas](#S-A)
51 * [N: Non-Rules and myths](#S-not)
52 * [RF: References](#S-references)
53 * [Pro: Profiles](#S-profile)
54 * [GSL: Guideline support library](#S-gsl)
55 * [NL: Naming and layout](#S-naming)
56 * [FAQ: Answers to frequently asked questions](#S-faq)
57 * [Appendix A: Libraries](#S-libraries)
58 * [Appendix B: Modernizing code](#S-modernizing)
59 * [Appendix C: Discussion](#S-discussion)
60 * [Glossary](#S-glossary)
61 * [To-do: Unclassified proto-rules](#S-unclassified)
63 You can sample rules for specific language features:
65 * assignment:
66 [regular types](#Rc-regular) --
67 [prefer initialization](#Rc-initialize) --
68 [copy](#Rc-copy-semantics) --
69 [move](#Rc-move-semantics) --
70 [other operations](Rc-matched) --
71 [default](#Rc-eqdefault)
72 * `class`:
73 [data](#Rc-org) --
74 [invariant](#Rc-struct) --
75 [members](#Rc-member) --
76 [helpers](#Rc-helper) --
77 [concrete types](#SS-concrete) --
78 [ctors, =, and dtors](#S-ctor) --
79 [hierarchy](#SS-hier) --
80 [operators](#SS-overload)
81 * `concept`:
82 [rules](#SS-concepts) --
83 [in generic programming](#Rt-raise) --
84 [template arguments](#RT-concepts) --
85 [semantics](#Rt-low)
86 * constructor:
87 [invariant](#Rc-struct) --
88 [establish invariant](#Rc-ctor) --
89 [`throw`](#Rc-throw) --
90 [default](#Rc-default0) --
91 [not needed](#Rc-default) --
92 [`explicit`](#Rc-explicit) --
93 [delegating](#Rc-delegating) --
94 [`virtual`](#RC-ctor-virtual)
95 * derived `class`:
96 [when to use](#Rh-domain) --
97 [as interface](#Rh-abstract) --
98 [destructors](#Rh-dtor) --
99 [copy](#Rh-copy) --
100 [getters and setters](#Rh-get) --
101 [multiple inheritance](#Rh-mi-interface) --
102 [overloading](#Rh-using) --
103 [slicing](#Rc-copy-virtual) --
104 [`dynamic_cast`](#Rh-dynamic_cast)
105 * destructor:
106 [and constructors](#Rc-matched) --
107 [when needed?](#Rc-dtor) --
108 [may not fail](#Rc-dtor-fail)
109 * exception:
110 [errors](#S-errors) --
111 [`throw`](Re-throw) --
112 [for errors only](#Re-errors) --
113 [`noexcept`](#Re-noexcept) --
114 [minimize `try`](#Re-catch) --
115 [what if no exceptions?](#Re-no-throw-codes)
116 * `for`:
117 [range-for and for](#Res-for-range) --
118 [for and while](#Res-for-while) --
119 [for-initializer](#Res-for-init) --
120 [empty body](#Res-empty) --
121 [loop variable](#Res-loop-counter) --
122 [loop variable type ???](#Res-???)
123 * function:
124 [naming](#Rf-package) --
125 [single operation](#Rf-logical) --
126 [no throw](#Rf-noexcept) --
127 [arguments](#Rf-smart) --
128 [argument passing](#Rf-conventional) --
129 [multiple return values](#Rf-out-multi) --
130 [pointers](#Rf-return-ptr) --
131 [lambdas](#Rf-capture-vs-overload)
132 * `inline`:
133 [small functions](#Rf-inline) --
134 [in headers](Rs-inline)
135 * initialization:
136 [always](#Res-always) --
137 [prefer `{}`](#Res-list) --
138 [lambdas](#Res-lambda-init) --
139 [in-class initializers](#Rc-in-class-initializer) --
140 [class members](#Rc-initialize) --
141 [factory functions](#Rc-factory)
142 * lambda expression:
143 [when to use](#SS-lambdas)
144 * operator:
145 [conventional](Ro-conventional) --
146 [avoid conversion operators](#Ro-conventional) --
147 [and lambdas](#Ro-lambda)
148 * `public`, `private`, and `protected`:
149 [information hiding](#Rc-private) --
150 [consistency](#Rh-public) --
151 [`protected`](#Rh-protected)
152 * `static_assert`:
153 [compile-time checking](#Rp-compile-time) --
154 [and concepts](#Rt-check-class)
155 * `struct`:
156 [for organizing data](#Rc-org) --
157 [use if no invariant](#Rc-struct) --
158 [no private members](#Rc-class)
159 * `template`:
160 [abstraction](#Rt-raise) --
161 [containers](#Rt-cont) --
162 [concepts](#Rt-concepts)
163 * `unsigned`:
164 [and signed](#Res-mix) --
165 [bit manipulation](#Res-unsigned)
166 * `virtual`:
167 [interfaces](#Ri-abstract) --
168 [not `virtual`](#Rc-concrete) --
169 [destructor](Rc-dtor-virtual) --
170 [never fail](#Rc-dtor-fail)
172 You can look at design concepts used to express the rules:
174 * assertion: ???
175 * error: ???
176 * exception: exception guarantee (???)
177 * failure: ???
178 * invariant: ???
179 * leak: ???
180 * library: ???
181 * precondition: ???
182 * postcondition: ???
183 * resource: ???
185 # <a name="S-abstract"></a>Abstract
187 This document is a set of guidelines for using C++ well.
188 The aim of this document is to help people to use modern C++ effectively.
189 By "modern C++" we mean C++11 and C++14 (and soon C++17).
190 In other words, what would you like your code to look like in 5 years' time, given that you can start now? In 10 years' time?
192 The guidelines are focused on relatively high-level issues, such as interfaces, resource management, memory management, and concurrency.
193 Such rules affect application architecture and library design.
194 Following the rules will lead to code that is statically type safe, has no resource leaks, and catches many more programming logic errors than is common in code today.
195 And it will run fast -- you can afford to do things right.
197 We are less concerned with low-level issues, such as naming conventions and indentation style.
198 However, no topic that can help a programmer is out of bounds.
200 Our initial set of rules emphasizes safety (of various forms) and simplicity.
201 They may very well be too strict.
202 We expect to have to introduce more exceptions to better accommodate real-world needs.
203 We also need more rules.
205 You will find some of the rules contrary to your expectations or even contrary to your experience.
206 If we haven't suggested you change your coding style in any way, we have failed!
207 Please try to verify or disprove rules!
208 In particular, we'd really like to have some of our rules backed up with measurements or better examples.
210 You will find some of the rules obvious or even trivial.
211 Please remember that one purpose of a guideline is to help someone who is less experienced or coming from a different background or language to get up to speed.
213 Many of the rules are designed to be supported by an analysis tool.
214 Violations of rules will be flagged with references (or links) to the relevant rule.
215 We do not expect you to memorize all the rules before trying to write code.
216 One way of thinking about these guidelines is as a specification for tools that happens to be readable by humans.
218 The rules are meant for gradual introduction into a code base.
219 We plan to build tools for that and hope others will too.
221 Comments and suggestions for improvements are most welcome.
222 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
224 # <a name="S-introduction"></a>In: Introduction
226 This is a set of core guidelines for modern C++, C++14, taking likely future enhancements and ISO Technical Specifications (TSs) into account.
227 The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
229 Introduction summary:
231 * [In.target: Target readership](#SS-readers)
232 * [In.aims: Aims](#SS-aims)
233 * [In.not: Non-aims](#SS-non)
234 * [In.force: Enforcement](#SS-force)
235 * [In.struct: The structure of this document](#SS-struct)
236 * [In.sec: Major sections](#SS-sec)
238 ## <a name="SS-readers"></a>In.target: Target readership
240 All C++ programmers. This includes [programmers who might consider C](#S-cpl).
242 ## <a name="SS-aims"></a>In.aims: Aims
244 The purpose of this document is to help developers to adopt modern C++ (C++11, C++14, and soon C++17) and to achieve a more uniform style across code bases.
246 We do not suffer the delusion that every one of these rules can be effectively applied to every code base. Upgrading old systems is hard. However, we do believe that a program that uses a rule is less error-prone and more maintainable than one that does not. Often, rules also lead to faster/easier initial development.
247 As far as we can tell, these rules lead to code that performs as well or better than older, more conventional techniques; they are meant to follow the zero-overhead principle ("what you don't use, you don't pay for" or "when you use an abstraction mechanism appropriately, you get at least as good performance as if you had handcoded using lower-level language constructs").
248 Consider these rules ideals for new code, opportunities to exploit when working on older code, and try to approximate these ideals as closely as feasible.
249 Remember:
251 ### <a name="R0"></a>In.0: Don't panic!
253 Take the time to understand the implications of a guideline rule on your program.
255 These guidelines are designed according to the "subset of superset" principle ([Stroustrup05](#Stroustrup05)).
256 They do not simply define a subset of C++ to be used (for reliability, safety, performance, or whatever).
257 Instead, they strongly recommend the use of a few simple "extensions" ([library components](#S-gsl))
258 that make the use of the most error-prone features of C++ redundant, so that they can be banned (in our set of rules).
260 The rules emphasize static type safety and resource safety.
261 For that reason, they emphasize possibilities for range checking, for avoiding dereferencing `nullptr`, for avoiding dangling pointers, and the systematic use of exceptions (via RAII).
262 Partly to achieve that and partly to minimize obscure code as a source of errors, the rules also emphasize simplicity and the hiding of necessary complexity behind well-specified interfaces.
264 Many of the rules are prescriptive.
265 We are uncomfortable with rules that simply state "don't do that!" without offering an alternative.
266 One consequence of that is that some rules can be supported only by heuristics, rather than precise and mechanically verifiable checks.
267 Other rules articulate general principles. For these more general rules, more detailed and specific rules provide partial checking.
269 These guidelines address the core of C++ and its use.
270 We expect that most large organizations, specific application areas, and even large projects will need further rules, possibly further restrictions, and further library support.
271 For example, hard real-time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
272 We encourage the development of such more specific rules as addenda to these core guidelines.
273 Build your ideal small foundation library and use that, rather than lowering your level of programming to glorified assembly code.
275 The rules are designed to allow [gradual adoption](#S-modernizing).
277 Some rules aim to increase various forms of safety while others aim to reduce the likelihood of accidents, many do both.
278 The guidelines aimed at preventing accidents often ban perfectly legal C++.
279 However, when there are two ways of expressing an idea and one has shown itself a common source of errors and the other has not, we try to guide programmers towards the latter.
281 ## <a name="SS-non"></a>In.not: Non-aims
283 The rules are not intended to be minimal or orthogonal.
284 In particular, general rules can be simple, but unenforceable.
285 Also, it is often hard to understand the implications of a general rule.
286 More specialized rules are often easier to understand and to enforce, but without general rules, they would just be a long list of special cases.
287 We provide rules aimed at helping novices as well as rules supporting expert use.
288 Some rules can be completely enforced, but others are based on heuristics.
290 These rules are not meant to be read serially, like a book.
291 You can browse through them using the links.
292 However, their main intended use is to be targets for tools.
293 That is, a tool looks for violations and the tool returns links to violated rules.
294 The rules then provide reasons, examples of potential consequences of the violation, and suggested remedies.
296 These guidelines are not intended to be a substitute for a tutorial treatment of C++.
297 If you need a tutorial for some given level of experience, see [the references](#S-references).
299 This is not a guide on how to convert old C++ code to more modern code.
300 It is meant to articulate ideas for new code in a concrete fashion.
301 However, see [the modernization section](#S-modernizing) for some possible approaches to modernizing/rejuvenating/upgrading.
302 Importantly, the rules support gradual adoption: It is typically infeasible to completely convert a large code base all at once.
304 These guidelines are not meant to be complete or exact in every language-technical detail.
305 For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
307 The rules are not intended to force you to write in an impoverished subset of C++.
308 They are *emphatically* not meant to define a, say, Java-like subset of C++.
309 They are not meant to define a single "one true C++" language.
310 We value expressiveness and uncompromised performance.
312 The rules are not value-neutral.
313 They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance.
314 They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance.
316 The rules are not perfect.
317 A rule can do harm by prohibiting something that is useful in a given situation.
318 A rule can do harm by failing to prohibit something that enables a serious error in a given situation.
319 A rule can do a lot of harm by being vague, ambiguous, unenforceable, or by enabling every solution to a problem.
320 It is impossible to completely meet the "do no harm" criteria.
321 Instead, our aim is the less ambitious: "Do the most good for most programmers";
322 if you cannot live with a rule, object to it, ignore it, but don't water it down until it becomes meaningless.
323 Also, suggest an improvement.
325 ## <a name="SS-force"></a>In.force: Enforcement
327 Rules with no enforcement are unmanageable for large code bases.
328 Enforcement of all rules is possible only for a small weak set of rules or for a specific user community.
330 * But we want lots of rules, and we want rules that everybody can use.
331 * But different people have different needs.
332 * But people don't like to read lots of rules.
333 * But people can't remember many rules.
335 So, we need subsetting to meet a variety of needs.
337 * But arbitrary subsetting leads to chaos.
339 We want guidelines that help a lot of people, make code more uniform, and strongly encourage people to modernize their code.
340 We want to encourage best practices, rather than leave all to individual choices and management pressures.
341 The ideal is to use all rules; that gives the greatest benefits.
343 This adds up to quite a few dilemmas.
344 We try to resolve those using tools.
345 Each rule has an **Enforcement** section listing ideas for enforcement.
346 Enforcement might be done by code review, by static analysis, by compiler, or by run-time checks.
347 Wherever possible, we prefer "mechanical" checking (humans are slow, inaccurate, and bore easily) and static checking.
348 Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed fat".
349 Where appropriate, we label a rule (in the **Enforcement** sections) with the name of groups of related rules (called "profiles").
350 A rule can be part of several profiles, or none.
351 For a start, we have a few profiles corresponding to common needs (desires, ideals):
353 * **type**: No type violations (reinterpreting a `T` as a `U` through casts, unions, or varargs)
354 * **bounds**: No bounds violations (accessing beyond the range of an array)
355 * **lifetime**: No leaks (failing to `delete` or multiple `delete`) and no access to invalid objects (dereferencing `nullptr`, using a dangling reference).
357 The profiles are intended to be used by tools, but also serve as an aid to the human reader.
358 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.
360 Tools that implement these rules shall respect the following syntax to explicitly suppress a rule:
362     [[gsl::suppress(tag)]]
364 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
365 name of a profile group-of-rules ("type", "bounds", or "lifetime"),
366 or a specific rule in a profile ([type.4](#Pro-type-cstylecast), or [bounds.2](#Pro-bounds-arrayindex)).
368 ## <a name="SS-struct"></a>In.struct: The structure of this document
370 Each rule (guideline, suggestion) can have several parts:
372 * The rule itself -- e.g., **no naked `new`**
373 * A rule reference number -- e.g., **C.7** (the 7th rule related to classes).
374   Since the major sections are not inherently ordered, we use letters as the first part of a rule reference "number".
375   We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
376 * **Reason**s (rationales) -- because programmers find it hard to follow rules they don't understand
377 * **Example**s -- because rules are hard to understand in the abstract; can be positive or negative
378 * **Alternative**s -- for "don't do this" rules
379 * **Exception**s -- we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
380 * **Enforcement** -- ideas about how the rule might be checked "mechanically"
381 * **See also**s -- references to related rules and/or further discussion (in this document or elsewhere)
382 * **Note**s (comments) -- something that needs saying that doesn't fit the other classifications
383 * **Discussion** -- references to more extensive rationale and/or examples placed outside the main lists of rules
385 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.
386 We hope that "mechanical" tools will improve with time to approximate what such an expert programmer notices.
387 Also, we assume that the rules will be refined over time to make them more precise and checkable.
389 A rule is aimed at being simple, rather than carefully phrased to mention every alternative and special case.
390 Such information is found in the **Alternative** paragraphs and the [Discussion](#S-discussion) sections.
391 If you don't understand a rule or disagree with it, please visit its **Discussion**.
392 If you feel that a discussion is missing or incomplete, enter an [Issue](https://github.com/isocpp/CppCoreGuidelines/issues)
393 explaining your concerns and possibly a corresponding PR.
395 This is not a language manual.
396 It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
397 Recommended information sources can be found in [the references](#S-references).
399 ## <a name="SS-sec"></a>In.sec: Major sections
401 * [In: Introduction](#S-introduction)
402 * [P: Philosophy](#S-philosophy)
403 * [I: Interfaces](#S-interfaces)
404 * [F: Functions](#S-functions)
405 * [C: Classes and class hierarchies](#S-class)
406 * [Enum: Enumerations](#S-enum)
407 * [R: Resource management](#S-resource)
408 * [ES: Expressions and statements](#S-expr)
409 * [E: Error handling](#S-errors)
410 * [Con: Constants and immutability](#S-const)
411 * [T: Templates and generic programming](#S-templates)
412 * [CP: Concurrency](#S-concurrency)
413 * [SL: The Standard library](#S-stdlib)
414 * [SF: Source files](#S-source)
415 * [CPL: C-style programming](#S-cpl)
416 * [Pro: Profiles](#S-profile)
417 * [GSL: Guideline support library](#S-gsl)
418 * [FAQ: Answers to frequently asked questions](#S-faq)
420 Supporting sections:
422 * [NL: Naming and layout](#S-naming)
423 * [Per: Performance](#S-performance)
424 * [N: Non-Rules and myths](#S-not)
425 * [RF: References](#S-references)
426 * [Appendix A: Libraries](#S-libraries)
427 * [Appendix B: Modernizing code](#S-modernizing)
428 * [Appendix C: Discussion](#S-discussion)
429 * [Glossary](#S-glossary)
430 * [To-do: Unclassified proto-rules](#S-unclassified)
432 These sections are not orthogonal.
434 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.
435 The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").
437 # <a name="S-philosophy"></a>P: Philosophy
439 The rules in this section are very general.
441 Philosophy rules summary:
443 * [P.1: Express ideas directly in code](#Rp-direct)
444 * [P.2: Write in ISO Standard C++](#Rp-Cplusplus)
445 * [P.3: Express intent](#Rp-what)
446 * [P.4: Ideally, a program should be statically type safe](#Rp-typesafe)
447 * [P.5: Prefer compile-time checking to run-time checking](#Rp-compile-time)
448 * [P.6: What cannot be checked at compile time should be checkable at run time](#Rp-run-time)
449 * [P.7: Catch run-time errors early](#Rp-early)
450 * [P.8: Don't leak any resources](#Rp-leak)
451 * [P.9: Don't waste time or space](#Rp-waste)
452 * [P.10: Prefer immutable data to mutable data](#Rp-mutable)
453 * [P.11: Encapsulate messy constructs, rather than spreading through the code](#Rp-library)
454 * [P.12: Use supporting tools as appropriate](#Rp-tools)
455 * [P.13: Use support libraries as appropriate](#Rp-lib)
457 Philosophical rules are generally not mechanically checkable.
458 However, individual rules reflecting these philosophical themes are.
459 Without a philosophical basis, the more concrete/specific/checkable rules lack rationale.
461 ### <a name="Rp-direct"></a>P.1: Express ideas directly in code
463 ##### Reason
465 Compilers don't read comments (or design documents) and neither do many programmers (consistently).
466 What is expressed in code has defined semantics and can (in principle) be checked by compilers and other tools.
468 ##### Example
470     class Date {
471         // ...
472     public:
473         Month month() const;  // do
474         int month();          // don't
475         // ...
476     };
478 The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object.
479 The second version leaves the reader guessing and opens more possibilities for uncaught bugs.
481 ##### Example
483     void f(vector<string>& v)
484     {
485         string val;
486         cin >> val;
487         // ...
488         int index = -1;                    // bad
489         for (int i = 0; i < v.size(); ++i)
490             if (v[i] == val) {
491                 index = i;
492                 break;
493             }
494         // ...
495     }
497 That loop is a restricted form of `std::find`.
498 A much clearer expression of intent would be:
500     void f(vector<string>& v)
501     {
502         string val;
503         cin >> val;
504         // ...
505         auto p = find(begin(v), end(v), val);  // better
506         // ...
507     }
509 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.
511 A C++ programmer should know the basics of the standard library, and use it where appropriate.
512 Any programmer should know the basics of the foundation libraries of the project being worked on, and use them appropriately.
513 Any programmer using these guidelines should know the [guideline support library](#S-gsl), and use it appropriately.
515 ##### Example
517     change_speed(double s);   // bad: what does s signify?
518     // ...
519     change_speed(2.3);
521 A better approach is to be explicit about the meaning of the double (new speed or delta on old speed?) and the unit used:
523     change_speed(Speed s);    // better: the meaning of s is specified
524     // ...
525     change_speed(2.3);        // error: no unit
526     change_speed(23m / 10s);  // meters per second
528 We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone.
529 If we wanted both absolute speed and deltas, we would have defined a `Delta` type.
531 ##### Enforcement
533 Very hard in general.
535 * use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
536 * flag uses of casts (casts neuter the type system)
537 * detect code that mimics the standard library (hard)
539 ### <a name="Rp-Cplusplus"></a>P.2: Write in ISO Standard C++
541 ##### Reason
543 This is a set of guidelines for writing ISO Standard C++.
545 ##### Note
547 There are environments where extensions are necessary, e.g., to access system resources.
548 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.
550 Extensions often do not have rigorously defined semantics.  Even extensions that
551 are common and implemented by multiple compilers may have slightly different
552 behaviors and edge case behavior as a direct result of *not* having a rigorous
553 standard definition.  With sufficient use of any such extension, expected
554 portability will be impacted.
556 ##### Note
558 Using valid ISO C++ does not guarantee portability (let alone correctness).
559 Avoid dependence on undefined behavior (e.g., [undefined order of evaluation](#Res-order))
560 and be aware of constructs with implementation defined meaning (e.g., `sizeof(int)`).
562 ##### Note
564 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.
565 In such cases, control their (dis)use with an extension of these Coding Guidelines customized to the specific environment.
567 ##### Enforcement
569 Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions.
571 ### <a name="Rp-what"></a>P.3: Express intent
573 ##### Reason
575 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.
577 ##### Example
579     int i = 0;
580     while (i < v.size()) {
581         // ... do something with v[i] ...
582     }
584 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.
586 Better:
588     for (const auto& x : v) { /* do something with the value of x */ }
590 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:
592     for (auto& x : v) { /* modify x */ }
594 Sometimes better still, use a named algorithm:
596     for_each(v, [](int x) { /* do something with the value of x */ });
597     for_each(par, v, [](int x) { /* do something with the value of x */ });
599 The last variant makes it clear that we are not interested in the order in which the elements of `v` are handled.
601 A programmer should be familiar with
603 * [The guideline support library](#S-gsl)
604 * [The ISO C++ standard library](#S-stdlib)
605 * Whatever foundation libraries are used for the current project(s)
607 ##### Note
609 Alternative formulation: Say what should be done, rather than just how it should be done.
611 ##### Note
613 Some language constructs express intent better than others.
615 ##### Example
617 If two `int`s are meant to be the coordinates of a 2D point, say so:
619     draw_line(int, int, int, int);  // obscure
620     draw_line(Point, Point);        // clearer
622 ##### Enforcement
624 Look for common patterns for which there are better alternatives
626 * simple `for` loops vs. range-`for` loops
627 * `f(T*, int)` interfaces vs. `f(span<T>)` interfaces
628 * loop variables in too large a scope
629 * naked `new` and `delete`
630 * functions with many parameters of built-in types
632 There is a huge scope for cleverness and semi-automated program transformation.
634 ### <a name="Rp-typesafe"></a>P.4: Ideally, a program should be statically type safe
636 ##### Reason
638 Ideally, a program would be completely statically (compile-time) type safe.
639 Unfortunately, that is not possible. Problem areas:
641 * unions
642 * casts
643 * array decay
644 * range errors
645 * narrowing conversions
647 ##### Note
649 These areas are sources of serious problems (e.g., crashes and security violations).
650 We try to provide alternative techniques.
652 ##### Enforcement
654 We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
655 Always suggest an alternative.
656 For example:
658 * unions -- use `variant` (in C++17)
659 * casts -- minimize their use; templates can help
660 * array decay -- use `span` (from the GSL)
661 * range errors -- use `span`
662 * narrowing conversions -- minimize their use and use `narrow` or `narrow_cast` (from the GSL) where they are necessary
664 ### <a name="Rp-compile-time"></a>P.5: Prefer compile-time checking to run-time checking
666 ##### Reason
668 Code clarity and performance.
669 You don't need to write error handlers for errors caught at compile time.
671 ##### Example
673     // Int is an alias used for integers
674     int bits = 0;         // don't: avoidable code
675     for (Int i = 1; i; i <<= 1)
676         ++bits;
677     if (bits < 32)
678         cerr << "Int too small\n"
680 This example is easily simplified
682     // Int is an alias used for integers
683     static_assert(sizeof(Int) >= 4);    // do: compile-time check
685 ##### Example
687     void read(int* p, int n);   // read max n integers into *p
689     int a[100];
690     read(a, 1000);    // bad
692 better
694     void read(span<int> r); // read into the range of integers r
696     int a[100];
697     read(a);        // better: let the compiler figure out the number of elements
699 **Alternative formulation**: Don't postpone to run time what can be done well at compile time.
701 ##### Enforcement
703 * Look for pointer arguments.
704 * Look for run-time checks for range violations.
706 ### <a name="Rp-run-time"></a>P.6: What cannot be checked at compile time should be checkable at run time
708 ##### Reason
710 Leaving hard-to-detect errors in a program is asking for crashes and bad results.
712 ##### Note
714 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).
716 ##### Example, bad
718     // separately compiled, possibly dynamically loaded
719     extern void f(int* p);
721     void g(int n)
722     {
723         // bad: the number of elements is not passed to f()
724         f(new int[n]);
725     }
727 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.
729 ##### Example, bad
731 We can of course pass the number of elements along with the pointer:
733     // separately compiled, possibly dynamically loaded
734     extern void f2(int* p, int n);
736     void g2(int n)
737     {
738         f2(new int[n], m);  // bad: a wrong number of elements can be passed to f()
739     }
741 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.
743 Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
745 ##### Example, bad
747 The standard library resource management pointers fail to pass the size when they point to an object:
749     // separately compiled, possibly dynamically loaded
750     // NB: this assumes the calling code is ABI-compatible, using a
751     // compatible C++ compiler and the same stdlib implementation
752     extern void f3(unique_ptr<int[]>, int n);
754     void g3(int n)
755     {
756         f3(make_unique<int[]>(n), m);    // bad: pass ownership and size separately
757     }
759 ##### Example
761 We need to pass the pointer and the number of elements as an integral object:
763     extern void f4(vector<int>&);   // separately compiled, possibly dynamically loaded
764     extern void f4(span<int>);      // separately compiled, possibly dynamically loaded
765                                     // NB: this assumes the calling code is ABI-compatible, using a
766                                     // compatible C++ compiler and the same stdlib implementation
768     void g3(int n)
769     {
770         vector<int> v(n);
771         f4(v);                     // pass a reference, retain ownership
772         f4(span<int>{v});          // pass a view, retain ownership
773     }
775 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.
777 ##### Example
779 How do we transfer both ownership and all information needed for validating use?
781     vector<int> f5(int n)    // OK: move
782     {
783         vector<int> v(n);
784         // ... initialize v ...
785         return v;
786     }
788     unique_ptr<int[]> f6(int n)    // bad: loses n
789     {
790         auto p = make_unique<int[]>(n);
791         // ... initialize *p ...
792         return p;
793     }
795     owner<int*> f7(int n)    // bad: loses n and we might forget to delete
796     {
797         owner<int*> p = new int[n];
798         // ... initialize *p ...
799         return p;
800     }
802 ##### Example
804 * ???
805 * show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
806   Or strings as "free-style" options
808 ##### Enforcement
810 * Flag (pointer, count)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
811 * ???
813 ### <a name="Rp-early"></a>P.7: Catch run-time errors early
815 ##### Reason
817 Avoid "mysterious" crashes.
818 Avoid errors leading to (possibly unrecognized) wrong results.
820 ##### Example
822     void increment1(int* p, int n)    // bad: error prone
823     {
824         for (int i = 0; i < n; ++i) ++p[i];
825     }
827     void use1(int m)
828     {
829         const int n = 10;
830         int a[n] = {};
831         // ...
832         increment1(a, m);   // maybe typo, maybe m <= n is supposed
833                             // but assume that m == 20
834         // ...
835     }
837 Here we made a small error in `use1` that will lead to corrupted data or a crash.
838 The (pointer, count)-style interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
839 If we could check subscripts for out of range access, then the error would not be discovered until `p[10]` was accessed.
840 We could check earlier and improve the code:
842     void increment2(span<int> p)
843     {
844         for (int& x : p) ++x;
845     }
847     void use2(int m)
848     {
849         const int n = 10;
850         int a[n] = {};
851         // ...
852         increment2({a, m});    // maybe typo, maybe m <= n is supposed
853         // ...
854     }
856 Now, `m<=n` can be checked at the point of call (early) rather than later.
857 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):
859     void use3(int m)
860     {
861         const int n = 10;
862         int a[n] = {};
863         // ...
864         increment2(a);   // the number of elements of a need not be repeated
865         // ...
866     }
868 ##### Example, bad
870 Don't repeatedly check the same value. Don't pass structured data as strings:
872     Date read_date(istream& is);    // read date from istream
874     Date extract_date(const string& s);    // extract date from string
876     void user1(const string& date)    // manipulate date
877     {
878         auto d = extract_date(date);
879         // ...
880     }
882     void user2()
883     {
884         Date d = read_date(cin);
885         // ...
886         user1(d.to_string());
887         // ...
888     }
890 The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data).
892 ##### Example
894 Excess checking can be costly.
895 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)`).
897     class Jet {    // Physics says: e * e < x * x + y * y + z * z
898         float x;
899         float y;
900         float z;
901         float e;
902     public:
903         Jet(float x, float y, float z, float e)
904             :x(x), y(y), z(z), e(e)
905         {
906             // Should I check here that the values are physically meaningful?
907         }
909         float m() const
910         {
911             // Should I handle the degenerate case here?
912             return sqrt(x * x + y * y + z * z - e * e);
913         }
915         ???
916     };
918 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.
922 ##### Enforcement
924 * Look at pointers and arrays: Do range-checking early and not repeatedly
925 * Look at conversions: Eliminate or mark narrowing conversions
926 * Look for unchecked values coming from input
927 * Look for structured data (objects of classes with invariants) being converted into strings
928 * ???
930 ### <a name="Rp-leak"></a>P.8: Don't leak any resources
932 ##### Reason
934 Even a slow growth in resources will, over time, exhaust the availability of those resources.
935 This is particularly important for long-running programs, but is an essential piece of responsible programming behavior.
937 ##### Example, bad
939     void f(char* name)
940     {
941         FILE* input = fopen(name, "r");
942         // ...
943         if (something) return;   // bad: if something == true, a file handle is leaked
944         // ...
945         fclose(input);
946     }
948 Prefer [RAII](#Rr-raii):
950     void f(char* name)
951     {
952         ifstream input {name};
953         // ...
954         if (something) return;   // OK: no leak
955         // ...
956     }
958 **See also**: [The resource management section](#S-resource)
960 ##### Note
962 A leak is colloquially "anything that isn't cleaned up."
963 The more important classification is "anything that can no longer be cleaned up."
964 For example, allocating an object on the heap and then losing the last pointer that points to that allocation.
965 This rule should not be taken as requiring that allocations within long-lived objects must be returned during program shutdown.
966 For example, relying on system guaranteed cleanup such as file closing and memory deallocation upon process shutdown can simplify code.
967 However, relying on abstractions that implicitly clean up can be as simple, and often safer.
969 ##### Note
971 Enforcing [the lifetime profile](#In.force) eliminates leaks.
972 When combined with resource safety provided by [RAII](#Rr-raii), it eliminates the need for "garbage collection" (by generating no garbage).
973 Combine this with enforcement of [the type and bounds profiles](#In.force) and you get complete type- and resource-safety, guaranteed by tools.
975 ##### Enforcement
977 * Look at pointers: Classify them into non-owners (the default) and owners.
978   Where feasible, replace owners with standard-library resource handles (as in the example above).
979   Alternatively, mark an owner as such using `owner` from [the GSL](#S-gsl).
980 * Look for naked `new` and `delete`
981 * Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
983 ### <a name="Rp-waste"></a>P.9: Don't waste time or space
985 ##### Reason
987 This is C++.
989 ##### Note
991 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.
992 "Another benefit of striving for efficiency is that the process forces you to understand the problem in more depth." - Alex Stepanov
994 ##### Example, bad
996     struct X {
997         char ch;
998         int i;
999         string s;
1000         char ch2;
1002         X& operator=(const X& a);
1003         X(const X&);
1004     };
1006     X waste(const char* p)
1007     {
1008         if (p == nullptr) throw Nullptr_error{};
1009         int n = strlen(p);
1010         auto buf = new char[n];
1011         if (buf == nullptr) throw Allocation_error{};
1012         for (int i = 0; i < n; ++i) buf[i] = p[i];
1013         // ... manipulate buffer ...
1014         X x;
1015         x.ch = 'a';
1016         x.s = string(n);    // give x.s space for *p
1017         for (int i = 0; i < x.s.size(); ++i) x.s[i] = buf[i];  // copy buf into x.s
1018         delete buf;
1019         return x;
1020     }
1022     void driver()
1023     {
1024         X x = waste("Typical argument");
1025         // ...
1026     }
1028 Yes, this is a caricature, but we have seen every individual mistake in production code, and worse.
1029 Note that the layout of `X` guarantees that at least 6 bytes (and most likely more) are wasted.
1030 The spurious definition of copy operations disables move semantics so that the return operation is slow
1031 (please note that the Return Value Optimization, RVO, is not guaranteed here).
1032 The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`.
1033 There are several more performance bugs and gratuitous complication.
1035 ##### Example, bad
1037     void lower(zstring s)
1038     {
1039         for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
1040     }
1042 Yes, this is an example from production code.
1043 We leave it to the reader to figure out what's wasted.
1045 ##### Note
1047 An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert.
1048 However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like.
1049 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.
1050 After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines.
1052 ##### Enforcement
1054 Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
1056 ### <a name="Rp-mutable"></a>P.10: Prefer immutable data to mutable data
1058 ##### Reason
1060 It is easier to reason about constants than about variables.
1061 Something immutable cannot change unexpectedly.
1062 Sometimes immutability enables better optimization.
1063 You can't have a data race on a constant.
1065 See [Con: Constants and Immutability](#S-const)
1067 ### <a name="Rp-library"></a>P.11: Encapsulate messy constructs, rather than spreading through the code
1069 ##### Reason
1071 Messy code is more likely to hide bugs and harder to write.
1072 A good interface is easier and safer to use.
1073 Messy, low-level code breeds more such code.
1075 ##### Example
1077     int sz = 100;
1078     int* p = (int*) malloc(sizeof(int) * sz);
1079     int count = 0;
1080     // ...
1081     for (;;) {
1082         // ... read an int into x, exit loop if end of file is reached ...
1083         // ... check that x is valid ...
1084         if (count == sz)
1085             p = (int*) realloc(p, sizeof(int) * sz * 2);
1086         p[count++] = x;
1087         // ...
1088     }
1090 This is low-level, verbose, and error-prone.
1091 For example, we "forgot" to test for memory exhaustion.
1092 Instead, we could use `vector`:
1094     vector<int> v;
1095     v.reserve(100);
1096     // ...
1097     for (int x; cin >> x; ) {
1098         // ... check that x is valid ...
1099         v.push_back(x);
1100     }
1102 ##### Note
1104 The standards library and the GSL are examples of this philosophy.
1105 For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, `gsl::owner`, etc.
1106 that are needed to implement key abstractions, such as `vector`, `span`, `lock_guard`, and `future`, we use the libraries
1107 designed and implemented by people with more time and expertise than we usually have.
1108 Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves)
1109 with the challenge of repeatedly getting low-level code well.
1110 This is a variant of the [subset of superset principle](#R0) that underlies these guidelines.
1112 ##### Enforcement
1114 * Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.
1117 ### <a name="Rp-tools"></a>P.12: Use supporting tools as appropriate
1119 ##### Reason
1121 There are many things that are done better "by machine".
1122 Computers don't tire or get bored by repetitive tasks.
1123 We typically have better things to do than repeatedly do routine tasks.
1125 ##### Example
1127 Run a static analyzer to verify that your code follows the guidelines you want it to follow.
1129 ##### Note
1133 * [Static analysis tools](???)
1134 * [Concurrency tools](#Rconc-tools)
1135 * [Testing tools](???)
1137 There are many other kinds of tools, such as source code depositories, build tools, etc.,
1138 but those are beyond the scope of these guidelines.
1140 ###### Note
1142 Be careful not to become dependent on over-elaborate or over-specialized tool chains.
1143 Those can make your otherwise portable code non-portable.
1146 ### <a name="Rp-lib"></a>P.13: Use support libraries as appropriate
1148 ##### Reason
1150 Using a well-designed, well-documented, and well-supported library saves time and effort;
1151 its quality and documentation are likely to be greater than what you could do
1152 if the majority of your time must be spent on an implementation.
1153 The cost (time, effort, money, etc.) of a library can be shared over many users.
1154 A widely used library is more likely to be kept up-to-date and ported to new systems than an individual application.
1155 Knowledge of a widely-used library can save time on other/future projects.
1156 So, if a suitable library exists for your application domain, use it.
1158 ##### Example
1160     std::sort(begin(v), end(v), std::greater<>());
1162 Unless you are an expert in sorting algorithms and have plenty of time,
1163 this is more likely to be correct and to run faster than anything you write for a specific application.
1164 You need a reason not to use the standard library (or whatever foundational libraries your application uses) rather than a reason to use it.
1166 ##### Note
1168 By default use
1170 * The [ISO C++ standard library](#S-stdlib)
1171 * The [Guidelines Support Library](#S-gsl)
1173 ##### Note
1175 If no well-designed, well-documented, and well-supported library exists for an important domain,
1176 maybe you should design and implement it, and then use it.
1179 # <a name="S-interfaces"></a>I: Interfaces
1181 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.
1182 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.
1184 Interface rule summary:
1186 * [I.1: Make interfaces explicit](#Ri-explicit)
1187 * [I.2: Avoid global variables](#Ri-global)
1188 * [I.3: Avoid singletons](#Ri-singleton)
1189 * [I.4: Make interfaces precisely and strongly typed](#Ri-typed)
1190 * [I.5: State preconditions (if any)](#Ri-pre)
1191 * [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
1192 * [I.7: State postconditions](#Ri-post)
1193 * [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
1194 * [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
1195 * [I.10: Use exceptions to signal a failure to perform a required task](#Ri-except)
1196 * [I.11: Never transfer ownership by a raw pointer (`T*`)](#Ri-raw)
1197 * [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
1198 * [I.13: Do not pass an array as a single pointer](#Ri-array)
1199 * [I.22: Avoid complex initialization of global objects](#Ri-global-init)
1200 * [I.23: Keep the number of function arguments low](#Ri-nargs)
1201 * [I.24: Avoid adjacent unrelated parameters of the same type](#Ri-unrelated)
1202 * [I.25: Prefer abstract classes as interfaces to class hierarchies](#Ri-abstract)
1203 * [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
1205 See also
1207 * [F: Functions](#S-functions)
1208 * [C.concrete: Concrete types](#SS-concrete)
1209 * [C.hier: Class hierarchies](#SS-hier)
1210 * [C.over: Overloading and overloaded operators](#SS-overload)
1211 * [C.con: Containers and other resource handles](#SS-containers)
1212 * [E: Error handling](#S-errors)
1213 * [T: Templates and generic programming](#S-templates)
1215 ### <a name="Ri-explicit"></a>I.1: Make interfaces explicit
1217 ##### Reason
1219 Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
1221 ##### Example, bad
1223 Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
1225     int rnd(double d)
1226     {
1227         return (rnd_up) ? ceil(d) : d;    // don't: "invisible" dependency
1228     }
1230 It will not be obvious to a caller that the meaning of two calls of `rnd(7.2)` might give different results.
1232 ##### Exception
1234 Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
1235 The use of a non-local control is potentially confusing, but controls only implementation details of otherwise fixed semantics.
1237 ##### Example, bad
1239 Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
1241     // don't: no test of printf's return value
1242     fprintf(connection, "logging: %d %d %d\n", x, y, s);
1244 What if the connection goes down so that no logging output is produced? See I.??.
1246 **Alternative**: Throw an exception. An exception cannot be ignored.
1248 **Alternative formulation**: Avoid passing information across an interface through non-local or implicit state.
1249 Note that non-`const` member functions pass information to other member functions through their object's state.
1251 **Alternative formulation**: An interface should be a function or a set of functions.
1252 Functions can be template functions and sets of functions can be classes or class templates.
1254 ##### Enforcement
1256 * (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.
1257 * (Simple) A function should not write to variables declared at namespace scope.
1259 ### <a name="Ri-global"></a>I.2 Avoid global variables
1261 ##### Reason
1263 Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
1265 ##### Example
1267     struct Data {
1268         // ... lots of stuff ...
1269     } data;            // non-const data
1271     void compute()     // don't
1272     {
1273         // ... use data ...
1274     }
1276     void output()     // don't
1277     {
1278         // ... use data ...
1279     }
1281 Who else might modify `data`?
1283 ##### Note
1285 Global constants are useful.
1287 ##### Note
1289 The rule against global variables applies to namespace scope variables as well.
1291 **Alternative**: If you use global (more generally namespace scope) data to avoid copying, consider passing the data as an object by reference to `const`.
1292 Another solution is to define the data as the state of some object and the operations as member functions.
1294 **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.
1295 Every pointer or reference to mutable data is a potential data race.
1297 ##### Note
1299 You cannot have a race condition on immutable data.
1301 **References**: See the [rules for calling functions](#SS-call).
1303 ##### Enforcement
1305 (Simple) Report all non-`const` variables declared at namespace scope.
1307 ### <a name="Ri-singleton"></a>I.3: Avoid singletons
1309 ##### Reason
1311 Singletons are basically complicated global objects in disguise.
1313 ##### Example
1315     class Singleton {
1316         // ... lots of stuff to ensure that only one Singleton object is created,
1317         // that it is initialized properly, etc.
1318     };
1320 There are many variants of the singleton idea.
1321 That's part of the problem.
1323 ##### Note
1325 If you don't want a global object to change, declare it `const` or `constexpr`.
1327 ##### Exception
1329 You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
1331     X& myX()
1332     {
1333         static X my_x {3};
1334         return my_x;
1335     }
1337 This is one of the most effective solutions to problems related to initialization order.
1338 In a multi-threaded environment, the initialization of the static object does not introduce a race condition
1339 (unless you carelessly access a shared object from within its constructor).
1341 Note that the initialization of a local `static` does not imply a race condition.
1342 However, if the destruction of `X` involves an operation that needs to be synchronized we must use a less simple solution.
1343 For example:
1345     X& myX()
1346     {
1347         static auto p = new X {3};
1348         return *p;  // potential leak
1349     }
1351 Now someone must `delete` that object in some suitably thread-safe way.
1352 That's error-prone, so we don't use that technique unless
1354 * `myX` is in multithreaded code,
1355 * that `X` object needs to be destroyed (e.g., because it releases a resource), and
1356 * `X`'s destructor's code needs to be synchronized.
1358 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.
1360 ##### Enforcement
1362 Very hard in general.
1364 * Look for classes with names that include `singleton`.
1365 * Look for classes for which only a single object is created (by counting objects or by examining constructors).
1366 * 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.
1368 ### <a name="Ri-typed"></a>I.4: Make interfaces precisely and strongly typed
1370 ##### Reason
1372 Types are the simplest and best documentation, have well-defined meaning, and are guaranteed to be checked at compile time.
1373 Also, precisely typed code is often optimized better.
1375 ##### Example, don't
1377 Consider:
1379     void pass(void* data);    // void* is suspicious
1381 Now the callee must cast the data pointer (back) to a correct type to use it. That is error-prone and often verbose.
1382 Avoid `void*`, especially in interfaces.
1383 Consider using a `variant` or a pointer to base instead.
1385 **Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or `T&`.
1386 For generic code these `T`s can be general or concept constrained template parameters.
1388 ##### Example, bad
1390 Consider:
1392     void draw_rect(int, int, int, int);   // great opportunities for mistakes
1394     draw_rect(p.x, p.y, 10, 20);          // what does 10, 20 mean?
1396 An `int` can carry arbitrary forms of information, so we must guess about the meaning of the four `int`s.
1397 Most likely, the first two are an `x`,`y` coordinate pair, but what are the last two?
1398 Comments and parameter names can help, but we could be explicit:
1400     void draw_rectangle(Point top_left, Point bottom_right);
1401     void draw_rectangle(Point top_left, Size height_width);
1403     draw_rectangle(p, Point{10, 20});  // two corners
1404     draw_rectangle(p, Size{10, 20});   // one corner and a (height, width) pair
1406 Obviously, we cannot catch all errors through the static type system
1407 (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
1409 ##### Example, bad
1411 In the following example, it is not clear from the interface what `time_to_blink` means: Seconds? Milliseconds?
1413     void blink_led(int time_to_blink) // bad -- the unit is ambiguous
1414     {
1415         // ...
1416         // do something with time_to_blink
1417         // ...
1418     }
1420     void use()
1421     {
1422         blink_led(2);
1423     }
1425 ##### Example, good
1427 `std::chrono::duration` types (C++11) helps making the unit of time duration explicit.
1429     void blink_led(milliseconds time_to_blink) // good -- the unit is explicit
1430     {
1431         // ...
1432         // do something with time_to_blink
1433         // ...
1434     }
1436     void use()
1437     {
1438         blink_led(1500ms);
1439     }
1441 The function can also be written in such a way that it will accept any time duration unit.
1443     template<class rep, class period>
1444     void blink_led(duration<rep, period> time_to_blink) // good -- accepts any unit
1445     {
1446         // assuming that millisecond is the smallest relevant unit
1447         auto milliseconds_to_blink = duration_cast<milliseconds>(time_to_blink);
1448         // ...
1449         // do something with milliseconds_to_blink
1450         // ...
1451     }
1453     void use()
1454     {
1455         blink_led(2s);
1456         blink_led(1500ms);
1457     }
1459 ##### Enforcement
1461 * (Simple) Report the use of `void*` as a parameter or return type.
1462 * (Hard to do well) Look for member functions with many built-in type arguments.
1464 ### <a name="Ri-pre"></a>I.5: State preconditions (if any)
1466 ##### Reason
1468 Arguments have meaning that may constrain their proper use in the callee.
1470 ##### Example
1472 Consider:
1474     double sqrt(double x);
1476 Here `x` must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
1478     double sqrt(double x); // x must be nonnegative
1480 Some preconditions can be expressed as assertions. For example:
1482     double sqrt(double x) { Expects(x >= 0); /* ... */ }
1484 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).
1486 **References**: `Expects()` is described in [GSL](#S-gsl).
1488 ##### Note
1490 Prefer a formal specification of requirements, such as `Expects(p != nullptr);`.
1491 If that is infeasible, use English text in comments, such as `// the sequence [p:q) is ordered using <`.
1493 ##### Note
1495 Most member functions have as a precondition that some class invariant holds.
1496 That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
1497 We don't need to mention it for each member function.
1499 ##### Enforcement
1501 (Not enforceable)
1503 **See also**: The rules for passing pointers. ???
1505 ### <a name="Ri-expects"></a>I.6: Prefer `Expects()` for expressing preconditions
1507 ##### Reason
1509 To make it clear that the condition is a precondition and to enable tool use.
1511 ##### Example
1513     int area(int height, int width)
1514     {
1515         Expects(height > 0 && width > 0);            // good
1516         if (height <= 0 || width <= 0) my_error();   // obscure
1517         // ...
1518     }
1520 ##### Note
1522 Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1523 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?).
1525 ##### Note
1527 Preconditions should be part of the interface rather than part of the implementation,
1528 but we don't yet have the language facilities to do that.
1529 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.
1531 ##### Note
1533 `Expects()` can also be used to check a condition in the middle of an algorithm.
1535 ##### Enforcement
1537 (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.
1539 ### <a name="Ri-post"></a>I.7: State postconditions
1541 ##### Reason
1543 To detect misunderstandings about the result and possibly catch erroneous implementations.
1545 ##### Example, bad
1547 Consider:
1549     int area(int height, int width) { return height * width; }  // bad
1551 Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
1552 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.
1553 Overflow can happen.
1554 Consider using:
1556     int area(int height, int width)
1557     {
1558         auto res = height * width;
1559         Ensures(res > 0);
1560         return res;
1561     }
1563 ##### Example, bad
1565 Consider a famous security bug:
1567     void f()    // problematic
1568     {
1569         char buffer[MAX];
1570         // ...
1571         memset(buffer, 0, MAX);
1572     }
1574 There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant `memset()` call:
1576     void f()    // better
1577     {
1578         char buffer[MAX];
1579         // ...
1580         memset(buffer, 0, MAX);
1581         Ensures(buffer[0] == 0);
1582     }
1584 ##### Note
1586 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.
1588 ##### Note
1590 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.
1592 ##### Example
1594 Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
1596     mutex m;
1598     void manipulate(Record& r)    // don't
1599     {
1600         m.lock();
1601         // ... no m.unlock() ...
1602     }
1604 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.
1605 Stating the postcondition would have made it clear:
1607     void manipulate(Record& r)    // postcondition: m is unlocked upon exit
1608     {
1609         m.lock();
1610         // ... no m.unlock() ...
1611     }
1613 The bug is now obvious (but only to a human reading comments).
1615 Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
1617     void manipulate(Record& r)    // best
1618     {
1619         lock_guard<mutex> _ {m};
1620         // ...
1621     }
1623 ##### Note
1625 Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
1626 Only postconditions related to the users can be stated in the interface.
1627 Postconditions related only to internal state belongs in the definition/implementation.
1629 ##### Enforcement
1631 (Not enforceable) This is a philosophical guideline that is infeasible to check
1632 directly in the general case. Domain specific checkers (like lock-holding
1633 checkers) exist for many toolchains.
1635 ### <a name="Ri-ensures"></a>I.8: Prefer `Ensures()` for expressing postconditions
1637 ##### Reason
1639 To make it clear that the condition is a postcondition and to enable tool use.
1641 ##### Example
1643     void f()
1644     {
1645         char buffer[MAX];
1646         // ...
1647         memset(buffer, 0, MAX);
1648         Ensures(buffer[0] == 0);
1649     }
1651 ##### Note
1653 Postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
1654 This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.
1656 **Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
1658 ##### Note
1660 Ideally, that `Ensures` should be part of the interface, but that's not easily done.
1661 For now, we place it in the definition (function body).
1662 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.
1664 ##### Enforcement
1666 (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.
1668 ### <a name="Ri-concepts"></a>I.9: If an interface is a template, document its parameters using concepts
1670 ##### Reason
1672 Make the interface precisely specified and compile-time checkable in the (not so distant) future.
1674 ##### Example
1676 Use the ISO Concepts TS style of requirements specification. For example:
1678     template<typename Iter, typename Val>
1679     // requires InputIterator<Iter> && EqualityComparable<ValueType<Iter>>, Val>
1680     Iter find(Iter first, Iter last, Val v)
1681     {
1682         // ...
1683     }
1685 ##### Note
1687 Soon (maybe in 2017), most compilers will be able to check `requires` clauses once the `//` is removed.
1688 For now, the concept TS is supported only in GCC 6.1.
1690 **See also**: [Generic programming](#SS-GP) and [concepts](#SS-t-concepts).
1692 ##### Enforcement
1694 (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).
1696 ### <a name="Ri-except"></a>I.10: Use exceptions to signal a failure to perform a required task
1698 ##### Reason
1700 It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
1701 This is a major source of errors.
1703 ##### Example
1705     int printf(const char* ...);    // bad: return negative number if output fails
1707     template <class F, class ...Args>
1708     // good: throw system_error if unable to start the new thread
1709     explicit thread(F&& f, Args&&... args);
1711 ##### Note
1713 What is an error?
1715 An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
1716 Calling code that ignores an error could lead to wrong results or undefined systems state.
1717 For example, not being able to connect to a remote server is not by itself an error:
1718 the server can refuse a connection for all kinds of reasons, so the natural thing is to return a result that the caller should always check.
1719 However, if failing to make a connection is considered an error, then a failure should throw an exception.
1721 ##### Exception
1723 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.
1725 ##### Alternative
1727 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:
1729     int val;
1730     int error_code;
1731     tie(val, error_code) = do_something();
1732     if (error_code == 0) {
1733         // ... handle the error or exit ...
1734     }
1735     // ... use val ...
1737 This style unfortunately leads to uninitialized variables.
1738 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.
1740     auto [val, error_code] = do_something();
1741     if (error_code == 0) {
1742         // ... handle the error or exit ...
1743     }
1744     // ... use val ...
1746 ##### Note
1748 We don't consider "performance" a valid reason not to use exceptions.
1750 * Often, explicit error checking and handling consume as much time and space as exception handling.
1751 * Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
1752 * A good rule for performance critical code is to move checking outside the critical part of the code ([checking](#Rper-checking)).
1753 * In the longer term, more regular code gets better optimized.
1754 * Always carefully [measure](#Rper-measure) before making performance claims.
1756 **See also**: [I.5](#Ri-pre) and [I.7](#Ri-post) for reporting precondition and postcondition violations.
1758 ##### Enforcement
1760 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1761 * Look for `errno`.
1763 ### <a name="Ri-raw"></a>I.11: Never transfer ownership by a raw pointer (`T*`)
1765 ##### Reason
1767 If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
1769 ##### Example
1771 Consider:
1773     X* compute(args)    // don't
1774     {
1775         X* res = new X{};
1776         // ...
1777         return res;
1778     }
1780 Who deletes the returned `X`? The problem would be harder to spot if compute returned a reference.
1781 Consider returning the result by value (use move semantics if the result is large):
1783     vector<double> compute(args)  // good
1784     {
1785         vector<double> res(10000);
1786         // ...
1787         return res;
1788     }
1790 **Alternative**: Pass ownership using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
1791 However, that is less elegant and less efficient unless reference semantics are needed.
1793 **Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
1794 In that case, mark owning pointers using `owner` from the [guideline support library](#S-gsl):
1796     owner<X*> compute(args)    // It is now clear that ownership is transferred
1797     {
1798         owner<X*> res = new X{};
1799         // ...
1800         return res;
1801     }
1803 This tells analysis tools that `res` is an owner.
1804 That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
1806 `owner` is used similarly in the implementation of resource handles.
1808 ##### Note
1810 Every object passed as a raw pointer (or iterator) is assumed to be owned by the
1811 caller, so that its lifetime is handled by the caller. Viewed another way:
1812 ownership transferring APIs are relatively rare compared to pointer-passing APIs,
1813 so the default is "no ownership transfer."
1815 **See also**: [Argument passing](#Rf-conventional) and [value return](#Rf-T-return).
1817 ##### Enforcement
1819 * (Simple) Warn on `delete` of a raw pointer that is not an `owner`.
1820 * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
1821 * (Simple) Warn if the return value of `new` or a function call with an `owner` return value is assigned to a raw pointer or non-`owner` reference.
1823 ### <a name="Ri-nullptr"></a>I.12: Declare a pointer that must not be null as `not_null`
1825 ##### Reason
1827 To help avoid dereferencing `nullptr` errors.
1828 To improve performance by avoiding redundant checks for `nullptr`.
1830 ##### Example
1832     int length(const char* p);            // it is not clear whether length(nullptr) is valid
1834     length(nullptr);                      // OK?
1836     int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr
1838     int length(const char* p);            // we must assume that p can be nullptr
1840 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.
1842 ##### Note
1844 `not_null` is defined in the [guideline support library](#S-gsl).
1846 ##### Note
1848 The assumption that the pointer to `char` pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use `czstring` in preference to `const char*`.
1850     // we can assume that p cannot be nullptr
1851     // we can assume that p points to a zero-terminated array of characters
1852     int length(not_null<zstring> p);
1854 Note: `length()` is, of course, `std::strlen()` in disguise.
1856 ##### Enforcement
1858 * (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`.
1859 * (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`.
1861 ### <a name="Ri-array"></a>I.13: Do not pass an array as a single pointer
1863 ##### Reason
1865  (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.
1867 ##### Example
1869 Consider:
1871     void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1873 What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
1874 What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
1875 Either is undefined behavior and a potentially very nasty bug.
1877 ##### Alternative
1879 Consider using explicit spans:
1881     void copy(span<const T> r, span<T> r2); // copy r to r2
1883 ##### Example, bad
1885 Consider:
1887     void draw(Shape* p, int n);  // poor interface; poor code
1888     Circle arr[10];
1889     // ...
1890     draw(arr, 10);
1892 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.
1894 **Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
1896     void draw2(span<Circle>);
1897     Circle arr[10];
1898     // ...
1899     draw2(span<Circle>(arr));  // deduce the number of elements
1900     draw2(arr);    // deduce the element type and array size
1902     void draw3(span<Shape>);
1903     draw3(arr);    // error: cannot convert Circle[10] to span<Shape>
1905 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 ???.
1907 ##### Exception
1909 Use `zstring` and `czstring` to represent a C-style, zero-terminated strings.
1910 But when doing so, use `string_span` from the [GSL](#GSL) to prevent range errors.
1912 ##### Enforcement
1914 * (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.
1915 * (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.
1917 ### <a name="Ri-global-init"></a>I.22: Avoid complex initialization of global objects
1919 ##### Reason
1921 Complex initialization can lead to undefined order of execution.
1923 ##### Example
1925     // file1.c
1927     extern const X x;
1929     const Y y = f(x);   // read x; write y
1931     // file2.c
1933     extern const Y y;
1935     const X x = g(y);   // read y; write x
1937 Since `x` and `y` are in different translation units the order of calls to `f()` and `g()` is undefined;
1938 one will access an uninitialized `const`.
1939 This shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global *variables*.
1941 ##### Note
1943 Order of initialization problems become particularly difficult to handle in concurrent code.
1944 It is usually best to avoid global (namespace scope) objects altogether.
1946 ##### Enforcement
1948 * Flag initializers of globals that call non-`constexpr` functions
1949 * Flag initializers of globals that access `extern` objects
1951 ### <a name="Ri-nargs"></a>I.23: Keep the number of function arguments low
1953 ##### Reason
1955 Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
1957 ##### Discussion
1959 The two most common reasons why functions have too many parameters are:
1961     1. *Missing an abstraction.* There is an abstraction missing, so that a compound value is being
1962     passed as individual elements instead of as a single object that enforces an invariant.
1963     This not only expands the parameter list, but it leads to errors because the component values
1964     are no longer protected by an enforced invariant.
1966     2. *Violating "one function, one responsibility."* The function is trying to do more than one
1967     job and should probably be refactored.
1969 ##### Example
1971 The standard-library `merge()` is at the limit of what we can comfortably handle:
1973     template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
1974     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
1975                          InputIterator2 first2, InputIterator2 last2,
1976                          OutputIterator result, Compare comp);
1978 Note that this is because of problem 1 above -- missing abstraction. Instead of passing a range (abstraction), STL passed iterator pairs (unencapsulated component values).
1980 Here, we have four template arguments and six function arguments.
1981 To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
1983     template<class InputIterator1, class InputIterator2, class OutputIterator>
1984     OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
1985                          InputIterator2 first2, InputIterator2 last2,
1986                          OutputIterator result);
1988 This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
1989 To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
1991     template<class InputRange1, class InputRange2, class OutputIterator>
1992     OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
1994 Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
1996 Alternatively, we could use concepts (as defined by the ISO TS) to define the notion of three types that must be usable for merging:
1998     Mergeable{In1 In2, Out}
1999     OutputIterator merge(In1 r1, In2 r2, Out result);
2001 ##### Example
2003 The safety Profiles recommend replacing
2005     void f(int* some_ints, int some_ints_length);  // BAD: C style, unsafe
2007 with
2009     void f(gsl::span<int> some_ints);              // GOOD: safe, bounds-checked
2011 Here, using an abstraction has safety and robustness benefits, and naturally also reduces the number of parameters.
2013 ##### Note
2015 How many parameters are too many? Try to use fewer than four (4) parameters.
2016 There are functions that are best expressed with four individual parameters, but not many.
2018 **Alternative**: Use better abstraction: Group arguments into meaningful objects and pass the objects (by value or by reference).
2020 **Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
2022 ##### Enforcement
2024 * Warn when a function declares two iterators (including pointers) of the same type instead of a range or a view.
2025 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
2027 ### <a name="Ri-unrelated"></a>I.24: Avoid adjacent unrelated parameters of the same type
2029 ##### Reason
2031 Adjacent arguments of the same type are easily swapped by mistake.
2033 ##### Example, bad
2035 Consider:
2037     void copy_n(T* p, T* q, int n);  // copy from [p:p+n) to [q:q+n)
2039 This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
2041 Use `const` for the "from" argument:
2043     void copy_n(const T* p, T* q, int n);  // copy from [p:p+n) to [q:q+n)
2045 ##### Exception
2047 If the order of the parameters is not important, there is no problem:
2049     int max(int a, int b);
2051 ##### Alternative
2053 Don't pass arrays as pointers, pass an object representing a range (e.g., a `span`):
2055     void copy_n(span<const T> p, span<T> q);  // copy from p to q
2057 ##### Alternative
2059 Define a `struct` as the parameter type and name the fields for those parameters accordingly:
2061     struct SystemParams {
2062         string config_file;
2063         string output_path;
2064         seconds timeout;
2065     };
2066     void initialize(SystemParams p);
2068 This tends to make invocations of this clear to future readers, as the parameters
2069 are often filled in by name at the call site.
2071 ##### Enforcement
2073 (Simple) Warn if two consecutive parameters share the same type.
2075 ### <a name="Ri-abstract"></a>I.25: Prefer abstract classes as interfaces to class hierarchies
2077 ##### Reason
2079 Abstract classes are more likely to be stable than base classes with state.
2081 ##### Example, bad
2083 You just knew that `Shape` would turn up somewhere :-)
2085     class Shape {  // bad: interface class loaded with data
2086     public:
2087         Point center() const { return c; }
2088         virtual void draw() const;
2089         virtual void rotate(int);
2090         // ...
2091     private:
2092         Point c;
2093         vector<Point> outline;
2094         Color col;
2095     };
2097 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:
2099     class Shape {    // better: Shape is a pure interface
2100     public:
2101         virtual Point center() const = 0;   // pure virtual function
2102         virtual void draw() const = 0;
2103         virtual void rotate(int) = 0;
2104         // ...
2105         // ... no data members ...
2106     };
2108 ##### Enforcement
2110 (Simple) Warn if a pointer/reference to a class `C` is assigned to a pointer/reference to a base of `C` and the base class contains data members.
2112 ### <a name="Ri-abi"></a>I.26: If you want a cross-compiler ABI, use a C-style subset
2114 ##### Reason
2116 Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
2118 ##### Exception
2120 You can carefully craft an interface using a few carefully selected higher-level C++ types. See ???.
2122 ##### Exception
2124 Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
2126 ##### Note
2128 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.
2130 ##### Enforcement
2132 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
2134 # <a name="S-functions"></a>F: Functions
2136 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.
2138 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.
2139 Functions are the most critical part in most interfaces, so see the interface rules.
2141 Function rule summary:
2143 Function definition rules:
2145 * [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
2146 * [F.2: A function should perform a single logical operation](#Rf-logical)
2147 * [F.3: Keep functions short and simple](#Rf-single)
2148 * [F.4: If a function may have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
2149 * [F.5: If a function is very small and time-critical, declare it inline](#Rf-inline)
2150 * [F.6: If your function may not throw, declare it `noexcept`](#Rf-noexcept)
2151 * [F.7: For general use, take `T*` or `T&` arguments rather than smart pointers](#Rf-smart)
2152 * [F.8: Prefer pure functions](#Rf-pure)
2153 * [F.9: Unused parameters should be unnamed](#Rf-unused)
2155 Parameter passing expression rules:
2157 * [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
2158 * [F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`](#Rf-in)
2159 * [F.17: For "in-out" parameters, pass by reference to non-`const`](#Rf-inout)
2160 * [F.18: For "consume" parameters, pass by `X&&` and `std::move` the parameter](#Rf-consume)
2161 * [F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter](#Rf-forward)
2162 * [F.20: For "out" output values, prefer return values to output parameters](#Rf-out)
2163 * [F.21: To return multiple "out" values, prefer returning a tuple or struct](#Rf-out-multi)
2164 * [F.60: Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
2166 Parameter passing semantic rules:
2168 * [F.22: Use `T*` or `owner<T*>` or a smart pointer to designate a single object](#Rf-ptr)
2169 * [F.23: Use a `not_null<T>` to indicate "null" is not a valid value](#Rf-nullptr)
2170 * [F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence](#Rf-range)
2171 * [F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string](#Rf-zstring)
2172 * [F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
2173 * [F.27: Use a `shared_ptr<T>` to share ownership](#Rf-shared_ptr)
2175 Value return semantic rules:
2177 * [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
2178 * [F.43: Never (directly or indirectly) return a pointer or a reference to a local object](#Rf-dangle)
2179 * [F.44: Return a `T&` when copy is undesirable and "returning no object" isn't an option](#Rf-return-ref)
2180 * [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
2181 * [F.46: `int` is the return type for `main()`](#Rf-main)
2182 * [F.47: Return `T&` from assignment operators.](#Rf-assignment-op)
2184 Other function rules:
2186 * [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)
2187 * [F.51: Where there is a choice, prefer default arguments over overloading](#Rf-default-args)
2188 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
2189 * [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)
2190 * [F.54: If you capture `this`, capture all variables explicitly (no default capture)](#Rf-this-capture)
2192 Functions have strong similarities to lambdas and function objects so see also Section ???.
2194 ## <a name="SS-fct-def"></a>F.def: Function definitions
2196 A function definition is a function declaration that also specifies the function's implementation, the function body.
2198 ### <a name="Rf-package"></a>F.1: "Package" meaningful operations as carefully named functions
2200 ##### Reason
2202 Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
2203 If something is a well-specified action, separate it out from its surrounding code and give it a name.
2205 ##### Example, don't
2207     void read_and_print(istream& is)    // read and print an int
2208     {
2209         int x;
2210         if (is >> x)
2211             cout << "the int is " << x << '\n';
2212         else
2213             cerr << "no int on input\n";
2214     }
2216 Almost everything is wrong with `read_and_print`.
2217 It reads, it writes (to a fixed `ostream`), it writes error messages (to a fixed `ostream`), it handles only `int`s.
2218 There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
2219 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
2220 mess could become hard to understand.
2222 ##### Note
2224 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.
2226 ##### Example
2228     sort(a, b, [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); });
2230 Naming that lambda breaks up the expression into its logical parts and provides a strong hint to the meaning of the lambda.
2232     auto lessT = [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); };
2234     sort(a, b, lessT);
2235     find_if(a, b, lessT);
2237 The shortest code is not always the best for performance or maintainability.
2239 ##### Exception
2241 Loop bodies, including lambdas used as loop bodies, rarely need to be named.
2242 However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
2243 The rule [Keep functions short](#Rf-single) implies "Keep loop bodies short."
2244 Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be re-usable.
2246 ##### Enforcement
2248 * See [Keep functions short](#Rf-single)
2249 * Flag identical and very similar lambdas used in different places.
2251 ### <a name="Rf-logical"></a>F.2: A function should perform a single logical operation
2253 ##### Reason
2255 A function that performs a single operation is simpler to understand, test, and reuse.
2257 ##### Example
2259 Consider:
2261     void read_and_print()    // bad
2262     {
2263         int x;
2264         cin >> x;
2265         // check for errors
2266         cout << x << "\n";
2267     }
2269 This is a monolith that is tied to a specific input and will never find another (different) use. Instead, break functions up into suitable logical parts and parameterize:
2271     int read(istream& is)    // better
2272     {
2273         int x;
2274         is >> x;
2275         // check for errors
2276         return x;
2277     }
2279     void print(ostream& os, int x)
2280     {
2281         os << x << "\n";
2282     }
2284 These can now be combined where needed:
2286     void read_and_print()
2287     {
2288         auto x = read(cin);
2289         print(cout, x);
2290     }
2292 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:
2294     auto read = [](auto& input, auto& value)    // better
2295     {
2296         input >> value;
2297         // check for errors
2298     };
2300     auto print(auto& output, const auto& value)
2301     {
2302         output << value << "\n";
2303     }
2305 ##### Enforcement
2307 * Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
2308 * Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
2309 * Consider functions with 7 or more parameters suspicious.
2311 ### <a name="Rf-single"></a>F.3: Keep functions short and simple
2313 ##### Reason
2315 Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
2316 Functions with complex control structures are more likely to be long and more likely to hide logical errors
2318 ##### Example
2320 Consider:
2322     double simpleFunc(double val, int flag1, int flag2)
2323         // simpleFunc: takes a value and calculates the expected ASIC output,
2324         // given the two mode flags.
2325     {
2326         double intermediate;
2327         if (flag1 > 0) {
2328             intermediate = func1(val);
2329             if (flag2 % 2)
2330                  intermediate = sqrt(intermediate);
2331         }
2332         else if (flag1 == -1) {
2333             intermediate = func1(-val);
2334             if (flag2 % 2)
2335                  intermediate = sqrt(-intermediate);
2336             flag1 = -flag1;
2337         }
2338         if (abs(flag2) > 10) {
2339             intermediate = func2(intermediate);
2340         }
2341         switch (flag2 / 10) {
2342             case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
2343                     break;
2344             case 2: return finalize(intermediate, 13.1);
2345             default: break;
2346         }
2347         return finalize(intermediate, 0.);
2348     }
2350 This is too complex (and long).
2351 How would you know if all possible alternatives have been correctly handled?
2352 Yes, it breaks other rules also.
2354 We can refactor:
2356     double func1_muon(double val, int flag)
2357     {
2358         // ???
2359     }
2361     double funct1_tau(double val, int flag1, int flag2)
2362     {
2363         // ???
2364     }
2366     double simpleFunc(double val, int flag1, int flag2)
2367         // simpleFunc: takes a value and calculates the expected ASIC output,
2368         // given the two mode flags.
2369     {
2370         if (flag1 > 0)
2371             return func1_muon(val, flag2);
2372         if (flag1 == -1)
2373             // handled by func1_tau: flag1 = -flag1;
2374             return func1_tau(-val, flag1, flag2);
2375         return 0.;
2376     }
2378 ##### Note
2380 "It doesn't fit on a screen" is often a good practical definition of "far too large."
2381 One-to-five-line functions should be considered normal.
2383 ##### Note
2385 Break large functions up into smaller cohesive and named functions.
2386 Small simple functions are easily inlined where the cost of a function call is significant.
2388 ##### Enforcement
2390 * Flag functions that do not "fit on a screen."
2391   How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
2392 * Flag functions that are too complex. How complex is too complex?
2393   You could use cyclomatic complexity. Try "more than 10 logical path through." Count a simple switch as one path.
2395 ### <a name="Rf-constexpr"></a>F.4: If a function may have to be evaluated at compile time, declare it `constexpr`
2397 ##### Reason
2399  `constexpr` is needed to tell the compiler to allow compile-time evaluation.
2401 ##### Example
2403 The (in)famous factorial:
2405     constexpr int fac(int n)
2406     {
2407         constexpr int max_exp = 17;      // constexpr enables max_exp to be used in Expects
2408         Expects(0 <= n && n < max_exp);  // prevent silliness and overflow
2409         int x = 1;
2410         for (int i = 2; i <= n; ++i) x *= i;
2411         return x;
2412     }
2414 This is C++14.
2415 For C++11, use a recursive formulation of `fac()`.
2417 ##### Note
2419 `constexpr` does not guarantee compile-time evaluation;
2420 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.
2422     constexpr int min(int x, int y) { return x < y ? x : y; }
2424     void test(int v)
2425     {
2426         int m1 = min(-1, 2);            // probably compile-time evaluation
2427         constexpr int m2 = min(-1, 2);  // compile-time evaluation
2428         int m3 = min(-1, v);            // run-time evaluation
2429         constexpr int m4 = min(-1, v);  // error: cannot evaluate at compile-time
2430     }
2432 ##### Note
2434 `constexpr` functions are pure: they can have no side effects.
2436     int dcount = 0;
2437     constexpr int double(int v)
2438     {
2439         ++dcount;   // error: attempted side effect from constexpr function
2440         return v + v;
2441     }
2443 This is usually a very good thing.
2445 When given a non-constant argument, a `constexpr` function can throw.
2446 If you consider exiting by throwing a side-effect, a `constexpr` function isn't completely pure;
2447 if not, this is not an issue.
2448 ??? A question for the committee: can a constructor for an exception thrown by a `constexpr` function modify state?
2449 "No" would be a nice answer that matches most practice.
2451 ##### Note
2453 Don't try to make all functions `constexpr`.
2454 Most computation is best done at run time.
2456 ##### Note
2458 Any API that may eventually depend on high-level runtime configuration or
2459 business logic should not be made `constexpr`. Such customization can not be
2460 evaluated by the compiler, and any `constexpr` functions that depended upon 
2461 that API would have to be refactored or drop `constexpr`.
2463 ##### Enforcement
2465 Impossible and unnecessary.
2466 The compiler gives an error if a non-`constexpr` function is called where a constant is required.
2468 ### <a name="Rf-inline"></a>F.5: If a function is very small and time-critical, declare it `inline`
2470 ##### Reason
2472 Some optimizers are good at inlining without hints from the programmer, but don't rely on it.
2473 Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
2474 We are still waiting.
2475 Specifying `inline` encourages the compiler to do a better job.
2477 ##### Example
2479     inline string cat(const string& s, const string& s2) { return s + s2; }
2481 ##### Exception
2483 Do not put an `inline` function in what is meant to be a stable interface unless you are certain that it will not change.
2484 An inline function is part of the ABI.
2486 ##### Note
2488 `constexpr` implies `inline`.
2490 ##### Note
2492 Member functions defined in-class are `inline` by default.
2494 ##### Exception
2496 Template functions (incl. template member functions) must be in headers and therefore inline.
2498 ##### Enforcement
2500 Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions).
2502 ### <a name="Rf-noexcept"></a>F.6: If your function may not throw, declare it `noexcept`
2504 ##### Reason
2506 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.
2508 ##### Example
2510 Put `noexcept` on every function written completely in C or in any other language without exceptions.
2511 The C++ standard library does that implicitly for all functions in the C standard library.
2513 ##### Note
2515 `constexpr` functions can throw when evaluated at run time, so you may need `noexcept` for some of those.
2517 ##### Example
2519 You can use `noexcept` even on functions that can throw:
2521     vector<string> collect(istream& is) noexcept
2522     {
2523         vector<string> res;
2524         for (string s; is >> s;)
2525             res.push_back(s);
2526         return res;
2527     }
2529 If `collect()` runs out of memory, the program crashes.
2530 Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do;
2531 `terminate()` may generate suitable error log information (but after memory runs out it is hard to do anything clever).
2533 ##### Note
2535 You must be aware of the execution environment that your code is running when
2536 deciding whether to tag a function `noexcept`, especially because of the issue
2537 of throwing and allocation.  Code that is intended to be perfectly general (like
2538 the standard library and other utility code of that sort) needs to support
2539 environments where a `bad_alloc` exception may be handled meaningfully.
2540 However, most programs and execution environments cannot meaningfully
2541 handle a failure to allocate, and aborting the program is the cleanest and
2542 simplest response to an allocation failure in those cases.  If you know that
2543 your application code cannot respond to an allocation failure, it may be
2544 appropriate to add `noexcept` even on functions that allocate.
2546 Put another way: In most programs, most functions can throw (e.g., because they
2547 use `new`, call functions that do, or use library functions that reports failure
2548 by throwing), so don't just sprinkle `noexcept` all over the place without
2549 considering whether the possible exceptions can be handled.
2551 `noexcept` is most useful (and most clearly correct) for frequently used,
2552 low-level functions.
2554 ##### Note
2556 Destructors, `swap` functions, move operations, and default constructors should never throw.
2558 ##### Enforcement
2560 * Flag functions that are not `noexcept`, yet cannot throw.
2561 * Flag throwing `swap`, `move`, destructors, and default constructors.
2563 ### <a name="Rf-smart"></a>F.7: For general use, take `T*` or `T&` arguments rather than smart pointers
2565 ##### Reason
2567 Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended (see [R.30](#Rr-smartptrparam)).
2568 Passing by smart pointer restricts the use of a function to callers that use smart pointers.
2569 Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
2571 ##### Example
2573     // accepts any int*
2574     void f(int*);
2576     // can only accept ints for which you want to transfer ownership
2577     void g(unique_ptr<int>);
2579     // can only accept ints for which you are willing to share ownership
2580     void g(shared_ptr<int>);
2582     // doesn't change ownership, but requires a particular ownership of the caller
2583     void h(const unique_ptr<int>&);
2585     // accepts any int
2586     void h(int&);
2588 ##### Example, bad
2590     // callee
2591     void f(shared_ptr<widget>& w)
2592     {
2593         // ...
2594         use(*w); // only use of w -- the lifetime is not used at all
2595         // ...
2596     };
2598 See further in [R.30](#Rr-smartptrparam).
2600 ##### Note
2602 We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.
2604 **See also**: [when to prefer `T*` and when to prefer `T&`](#Rf-ptr-ref).
2606 **See also**: Discussion of [smart pointer use](#Rr-summary-smartptrs).
2608 ##### Enforcement
2610 Flag a parameter of a smart pointer type (a type that overloads `operator->` or `operator*`) for which the ownership semantics are not used;
2611 that is
2613 * copyable but never copied/moved from or movable but never moved
2614 * and that is never modified or passed along to another function that could do so.
2616 ### <a name="Rf-pure"></a>F.8: Prefer pure functions
2618 ##### Reason
2620 Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
2622 ##### Example
2624     template<class T>
2625     auto square(T t) { return t * t; }
2627 ##### Note
2629 `constexpr` functions are pure.
2631 When given a non-constant argument, a `constexpr` function can throw.
2632 If you consider exiting by throwing a side-effect, a `constexpr` function isn't completely pure;
2633 if not, this is not an issue.
2634 ??? A question for the committee: can a constructor for an exception thrown by a `constexpr` function modify state?
2635 "No" would be a nice answer that matches most practice.
2637 ##### Enforcement
2639 Not possible.
2641 ### <a name="Rf-unused"></a>F.9: Unused parameters should be unnamed
2643 ##### Reason
2645 Readability.
2646 Suppression of unused parameter warnings.
2648 ##### Example
2650     X* find(map<Blob>& m, const string& s, Hint);   // once upon a time, a hint was used
2652 ##### Note
2654 Allowing parameters to be unnamed was introduced in the early 1980 to address this problem.
2656 ##### Enforcement
2658 Flag named unused parameters.
2660 ## <a name="SS-call"></a>F.call: Parameter passing
2662 There are a variety of ways to pass parameters to a function and to return values.
2664 ### <a name="Rf-conventional"></a>F.15: Prefer simple and conventional ways of passing information
2666 ##### Reason
2668 Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
2669 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.
2671 The following tables summarize the advice in the following Guidelines, F.16-21.
2673 Normal parameter passing:
2675 ![Normal parameter passing table](./param-passing-normal.png "Normal parameter passing")
2677 Advanced parameter passing:
2679 ![Advanced parameter passing table](./param-passing-advanced.png "Advanced parameter passing")
2681 Use the advanced techniques only after demonstrating need, and document that need in a comment.
2683 ### <a name="Rf-in"></a>F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`
2685 ##### Reason
2687 Both let the caller know that a function will not modify the argument, and both allow initialization by rvalues.
2689 What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
2690 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.
2692 ##### Example
2694     void f1(const string& s);  // OK: pass by reference to const; always cheap
2696     void f2(string s);         // bad: potentially expensive
2698     void f3(int x);            // OK: Unbeatable
2700     void f4(const int& x);     // bad: overhead on access in f4()
2702 For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
2704 * If the function is going to unconditionally move from the argument, take it by `&&`. See [F.18](#Rf-consume).
2705 * If the function is going to keep a copy of the argument, in addition to passing by `const&` (for lvalues),
2706   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).
2707 * In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See [F.19](#Rf-forward).
2709 ##### Example
2711     int multiply(int, int); // just input ints, pass by value
2713     // suffix is input-only but not as cheap as an int, pass by const&
2714     string& concatenate(string&, const string& suffix);
2716     void sink(unique_ptr<widget>);  // input only, and consumes the widget
2718 Avoid "esoteric techniques" such as:
2720 * Passing arguments as `T&&` "for efficiency".
2721   Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.25](#Rf-pass-ref-move).)
2722 * Returning `const T&` from assignments and similar operations (see [F.47](#Rf-assignment-op).)
2724 ##### Example
2726 Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`):
2728     Matrix operator+(const Matrix& a, const Matrix& b)
2729     {
2730         Matrix res;
2731         // ... fill res with the sum ...
2732         return res;
2733     }
2735     Matrix x = m1 + m2;  // move constructor
2737     y = m3 + m3;         // move assignment
2739 ##### Notes
2741 The return value optimization doesn't handle the assignment case, but the move assignment does.
2743 A reference may be assumed to refer to a valid object (language rule).
2744 There is no (legitimate) "null reference."
2745 If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
2747 ##### Enforcement
2749 * (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `4 * sizeof(int)`.
2750   Suggest using a reference to `const` instead.
2751 * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference has a size less than `3 * sizeof(int)`. Suggest passing by value instead.
2752 * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference is `move`d.
2754 ### <a name="Rf-inout"></a>F.17: For "in-out" parameters, pass by reference to non-`const`
2756 ##### Reason
2758 This makes it clear to callers that the object is assumed to be modified.
2760 ##### Example
2762     void update(Record& r);  // assume that update writes to r
2764 ##### Note
2766 A `T&` argument can pass information into a function as well as well as out of it.
2767 Thus `T&` could be an in-out-parameter. That can in itself be a problem and a source of errors:
2769     void f(string& s)
2770     {
2771         s = "New York";  // non-obvious error
2772     }
2774     void g()
2775     {
2776         string buffer = ".................................";
2777         f(buffer);
2778         // ...
2779     }
2781 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).
2782 A bad logic error can happen if the writer of `g()` incorrectly assumes the size of the `buffer`.
2784 ##### Enforcement
2786 * (Moderate) ((Foundation)) Warn about functions regarding reference to non-`const` parameters that do *not* write to them.
2787 * (Simple) ((Foundation)) Warn when a non-`const` parameter being passed by reference is `move`d.
2789 ### <a name="Rf-consume"></a>F.18: For "consume" parameters, pass by `X&&` and `std::move` the parameter
2791 ##### Reason
2793 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.
2795 ##### Example
2797     void sink(vector<int>&& v) {   // sink takes ownership of whatever the argument owned
2798         // usually there might be const accesses of v here
2799         store_somewhere(std::move(v));
2800         // usually no more use of v here; it is moved-from
2801     }
2803 Note that the `std::move(v)` makes it possible for `store_somewhere()` to leave `v` in a moved-from state.
2804 [That could be dangerous](#Rc-move-semantic).
2807 ##### Exception
2809 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.
2811 For example:
2813     template <class T>
2814     void sink(std::unique_ptr<T> p) {
2815         // use p ... possibly std::move(p) onward somewhere else
2816     }   // p gets destroyed
2818 ##### Enforcement
2820 * Flag all `X&&` parameters (where `X` is not a template type parameter name) where the function body uses them without `std::move`.
2821 * Flag access to moved-from objects.
2822 * Don't conditionally move from objects
2824 ### <a name="Rf-forward"></a>F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter
2826 ##### Reason
2828 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.
2830 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.
2832 ##### Example
2834     template <class F, class... Args>
2835     inline auto invoke(F f, Args&&... args) {
2836         return f(forward<Args>(args)...);
2837     }
2839     ??? calls ???
2841 ##### Enforcement
2843 * 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.
2845 ### <a name="Rf-out"></a>F.20: For "out" output values, prefer return values to output parameters
2847 ##### Reason
2849 A return value is self-documenting, whereas a `&` could be either in-out or out-only and is liable to be misused.
2851 This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
2853 If you have multiple values to return, [use a tuple](#Rf-out-multi) or similar multi-member type.
2855 ##### Example
2857     // OK: return pointers to elements with the value x
2858     vector<const int*> find_all(const vector<int>&, int x);
2860     // Bad: place pointers to elements with value x in out
2861     void find_all(const vector<int>&, vector<const int*>& out, int x);
2863 ##### Note
2865 A `struct` of many (individually cheap-to-move) elements may be in aggregate expensive to move.
2867 It is not recommended to return a `const` value.
2868 Such older advice is now obsolete; it does not add value, and it interferes with move semantics.
2870     const vector<int> fct();    // bad: that "const" is more trouble than it is worth
2872     vector<int> g(const vector<int>& vx)
2873     {
2874         // ...
2875         f() = vx;   // prevented by the "const"
2876         // ...
2877         return f(); // expensive copy: move semantics suppressed by the "const"
2878     }
2880 The argument for adding `const` to a return value is that it prevents (very rare) accidental access to a temporary.
2881 The argument against is prevents (very frequent) use of move semantics.
2883 ##### Exceptions
2885 * For non-value types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
2886 * 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).
2887 * 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).
2889 ##### Example
2891     struct Package {      // exceptional case: expensive-to-move object
2892         char header[16];
2893         char load[2024 - 16];
2894     };
2896     Package fill();       // Bad: large return value
2897     void fill(Package&);  // OK
2899     int val();            // OK
2900     void val(int&);       // Bad: Is val reading its argument
2902 ##### Enforcement
2904 * 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.
2905 * Flag returning a `const` value. To fix: Remove `const` to return a non-`const` value instead.
2907 ### <a name="Rf-out-multi"></a>F.21: To return multiple "out" values, prefer returning a tuple or struct
2909 ##### Reason
2911 A return value is self-documenting as an "output-only" value.
2912 Note that C++ does have multiple return values, by convention of using a `tuple` (including `pair`),
2913 possibly with the extra convenience of `tie` at the call site.
2915 ##### Example
2917     // BAD: output-only parameter documented in a comment
2918     int f(const string& input, /*output only*/ string& output_data)
2919     {
2920         // ...
2921         output_data = something();
2922         return status;
2923     }
2925     // GOOD: self-documenting
2926     tuple<int, string> f(const string& input)
2927     {
2928         // ...
2929         return make_tuple(status, something());
2930     }
2932 C++98's standard library already used this style, because a `pair` is like a two-element `tuple`.
2933 For example, given a `set<string> my_set`, consider:
2935     // C++98
2936     result = my_set.insert("Hello");
2937     if (result.second) do_something_with(result.first);    // workaround
2939 With C++11 we can write this, putting the results directly in existing local variables:
2941     Sometype iter;                                // default initialize if we haven't already
2942     Someothertype success;                        // used these variables for some other purpose
2944     tie(iter, success) = my_set.insert("Hello");   // normal return value
2945     if (success) do_something_with(iter);
2947 With C++17 we should be able to use "structured bindings" to declare and initialize the multiple variables:
2949     if (auto [ iter, success ] = my_set.insert("Hello"); success) do_something_with(iter);
2951 ##### Exception
2953 Sometimes, we need to pass an object to a function to manipulate its state.
2954 In such cases, passing the object by reference [`T&`](#Rf-inout) is usually the right technique.
2955 Explicitly passing an in-out parameter back out again as a return value is often not necessary.
2956 For example:
2958     istream& operator>>(istream& is, string& s);    // much like std::operator>>()
2960     for (string s; cin >> s; ) {
2961         // do something with line
2962     }
2964 Here, both `s` and `cin` are used as in-out parameters.
2965 We pass `cin` by (non-`const`) reference to be able to manipulate its state.
2966 We pass `s` to avoid repeated allocations.
2967 By reusing `s` (passed by reference), we allocate new memory only when we need to expand `s`'s capacity.
2968 This technique is sometimes called the "caller-allocated out" pattern and is particularly useful for types,
2969 such as `string` and `vector`, that needs to do free store allocations.
2971 To compare, if we passed out all values as return values, we would something like this:
2973     pair<istream&, string> get_string(istream& is);  // not recommended
2974     {
2975         string s;
2976         cin >> s;
2977         return {is, s};
2978     }
2980     for (auto p = get_string(cin); p.first; ) {
2981         // do something with p.second
2982     }
2984 We consider that significantly less elegant with significantly less performance.
2986 For a truly strict reading of this rule (F.21), the exception isn't really an exception because it relies on in-out parameters,
2987 rather than the plain out parameters mentioned in the rule.
2988 However, we prefer to be explicit, rather than subtle.
2990 ##### Note
2992 In many cases, it may be useful to return a specific, user-defined type.
2993 For example:
2995     struct Distance {
2996         int value;
2997         int unit = 1;   // 1 means meters
2998     };
3000     Distance d1 = measure(obj1);        // access d1.value and d1.unit
3001     auto d2 = measure(obj2);            // access d2.value and d2.unit
3002     auto [value, unit] = measure(obj3); // access value and unit; somewhat redundant
3003                                         // to people who know measure()
3004     auto [x, y] = measure(obj4);        // don't; it's likely to be confusing
3006 The overly-generic `pair` and `tuple` should be used only when the value returned represents to independent entities rather than an abstraction.
3008 Another example, use a specific type along the lines of `variant<T, error_code>`, rather than using the generic `tuple`.
3010 ##### Enforcement
3012 * Output parameters should be replaced by return values.
3013   An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
3015 ### <a name="Rf-ptr"></a>F.22: Use `T*` or `owner<T*>` to designate a single object
3017 ##### Reason
3019 Readability: it makes the meaning of a plain pointer clear.
3020 Enables significant tool support.
3022 ##### Note
3024 In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as:
3026 * Identify a (single) object (not to be deleted by this function)
3027 * Point to an object allocated on the free store (and delete it later)
3028 * Hold the `nullptr`
3029 * Identify a C-style string (zero-terminated array of characters)
3030 * Identify an array with a length specified separately
3031 * Identify a location in an array
3033 This makes it hard to understand what the code does and is supposed to do.
3034 It complicates checking and tool support.
3036 ##### Example
3038     void use(int* p, int n, char* s, int* q)
3039     {
3040         p[n - 1] = 666; // Bad: we don't know if p points to n elements;
3041                         // assume it does not or use span<int>
3042         cout << s;      // Bad: we don't know if that s points to a zero-terminated array of char;
3043                         // assume it does not or use zstring
3044         delete q;       // Bad: we don't know if *q is allocated on the free store;
3045                         // assume it does not or use owner
3046     }
3048 better
3050     void use2(span<int> p, zstring s, owner<int*> q)
3051     {
3052         p[p.size() - 1] = 666; // OK, a range error can be caught
3053         cout << s; // OK
3054         delete q;  // OK
3055     }
3057 ##### Note
3059 `owner<T*>` represents ownership, `zstring` represents a C-style string.
3061 **Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr<T>`) points to a single element.
3063 **See also**: [Support library](#S-gsl).
3065 ##### Enforcement
3067 * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
3069 ### <a name="Rf-nullptr"></a>F.23: Use a `not_null<T>` to indicate that "null" is not a valid value
3071 ##### Reason
3073 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.
3074 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`.
3076 ##### Example
3078 `not_null<T*>` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
3079 Additionally, when debugging, `owner<T*>` and `not_null<T>` can be instrumented to check for correctness.
3081 Consider:
3083     int length(Record* p);
3085 When I call `length(p)` should I test for `p == nullptr` first? Should the implementation of `length()` test for `p == nullptr`?
3087     // it is the caller's job to make sure p != nullptr
3088     int length(not_null<Record*> p);
3090     // the implementor of length() must assume that p == nullptr is possible
3091     int length(Record* p);
3093 ##### Note
3095 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).
3097 ##### Note
3099 `not_null` is not just for built-in pointers. It works for `unique_ptr`, `shared_ptr`, and other pointer-like types.
3101 ##### Enforcement
3103 * (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.
3104 * (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
3105 * (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
3107 ### <a name="Rf-range"></a>F.24: Use a `span<T>` or a `span_p<T>` to designate a half-open sequence
3109 ##### Reason
3111 Informal/non-explicit ranges are a source of errors.
3113 ##### Example
3115     X* find(span<X> r, const X& v);    // find v in r
3117     vector<X> vec;
3118     // ...
3119     auto p = find({vec.begin(), vec.end()}, X{});  // find X{} in vec
3121 ##### Note
3123 Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure.
3124 In particular, given a pair of arguments `(p, n)` designating an array \[`p`:`p+n`),
3125 it is in general impossible to know if there really are `n` elements to access following `*p`.
3126 `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.
3128 ##### Example
3130 A `span` represents a range of elements, but how do we manipulate elements of that range?
3132     void f(span<int> s)
3133     {
3134         // range traversal (guaranteed correct)
3135         for (int x : s) cout << x << '\n';
3137         // C-style traversal (potentially checked)
3138         for (int i = 0; i < s.size(); ++i) cout << s[i] << '\n';
3140         // random access (potentially checked)
3141         s[7] = 9;
3143         // extract pointers (potentially checked)
3144         std::sort(&s[0], &s[s.size() / 2]);
3145     }
3147 ##### Note
3149 A `span<T>` object does not own its elements and is so small that it can be passed by value.
3151 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.
3153 **See also**: [Support library](#S-gsl).
3155 ##### Enforcement
3157 (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `span` instead.
3159 ### <a name="Rf-zstring"></a>F.25: Use a `zstring` or a `not_null<zstring>` to designate a C-style string
3161 ##### Reason
3163 C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters.
3164 We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.
3166 ##### Example
3168 Consider:
3170     int length(const char* p);
3172 When I call `length(s)` should I test for `s == nullptr` first? Should the implementation of `length()` test for `p == nullptr`?
3174     // the implementor of length() must assume that p == nullptr is possible
3175     int length(zstring p);
3177     // it is the caller's job to make sure p != nullptr
3178     int length(not_null<zstring> p);
3180 ##### Note
3182 `zstring` do not represent ownership.
3184 **See also**: [Support library](#S-gsl).
3186 ### <a name="Rf-unique_ptr"></a>F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed
3188 ##### Reason
3190 Using `unique_ptr` is the cheapest way to pass a pointer safely.
3192 See also [C.50](#Rc-factory) regarding when to return a `shared_ptr` from a factory.
3194 ##### Example
3196     unique_ptr<Shape> get_shape(istream& is)  // assemble shape from input stream
3197     {
3198         auto kind = read_header(is); // read header and identify the next shape on input
3199         switch (kind) {
3200         case kCircle:
3201             return make_unique<Circle>(is);
3202         case kTriangle:
3203             return make_unique<Triangle>(is);
3204         // ...
3205         }
3206     }
3208 ##### Note
3210 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).
3212 ##### Enforcement
3214 (Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead.
3216 ### <a name="Rf-shared_ptr"></a>F.27: Use a `shared_ptr<T>` to share ownership
3218 ##### Reason
3220 Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object.
3222 ##### Example
3224     shared_ptr<const Image> im { read_image(somewhere) };
3226     std::thread t0 {shade, args0, top_left, im};
3227     std::thread t1 {shade, args1, top_right, im};
3228     std::thread t2 {shade, args2, bottom_left, im};
3229     std::thread t3 {shade, args3, bottom_right, im};
3231     // detach threads
3232     // last thread to finish deletes the image
3234 ##### Note
3236 Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time.
3237 `shared_ptr` is for shared ownership.
3239 Note that pervasive use of `shared_ptr` has a cost (atomic operations on the `shared_ptr`'s reference count have a measurable aggregate cost).
3241 ##### Alternative
3243 Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.
3245 ##### Enforcement
3247 (Not enforceable) This is a too complex pattern to reliably detect.
3249 ### <a name="Rf-ptr-ref"></a>F.60: Prefer `T*` over `T&` when "no argument" is a valid option
3251 ##### Reason
3253 A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference".
3254 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.
3256 ##### Example
3258     string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
3259     {
3260         if (p == nullptr) return string{};    // p might be nullptr; remember to check
3261         return string{p};
3262     }
3264     void print(const vector<int>& r)
3265     {
3266         // r refers to a vector<int>; no check needed
3267     }
3269 ##### Note
3271 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;`).
3272 That error is very uncommon.
3274 ##### Note
3276 If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null<T*>` provides the same guarantee as `T&`.
3278 ##### Enforcement
3280 * Flag ???
3282 ### <a name="Rf-return-ptr"></a>F.42: Return a `T*` to indicate a position (only)
3284 ##### Reason
3286 That's what pointers are good for.
3287 Returning a `T*` to transfer ownership is a misuse.
3289 ##### Example
3291     Node* find(Node* t, const string& s)  // find s in a binary tree of Nodes
3292     {
3293         if (t == nullptr || t->name == s) return t;
3294         if ((auto p = find(t->left, s))) return p;
3295         if ((auto p = find(t->right, s))) return p;
3296         return nullptr;
3297     }
3299 If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`.
3300 Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.
3302 ##### Note
3304 Positions can also be transferred by iterators, indices, and references.
3305 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](???).
3307 ##### Note
3309 Do not return a pointer to something that is not in the caller's scope; see [F.43](#Rf-dangle).
3311 **See also**: [discussion of dangling pointer prevention](#???).
3313 ##### Enforcement
3315 * Flag `delete`, `std::free()`, etc. applied to a plain `T*`.
3316 Only owners should be deleted.
3317 * Flag `new`, `malloc()`, etc. assigned to a plain `T*`.
3318 Only owners should be responsible for deletion.
3320 ### <a name="Rf-dangle"></a>F.43: Never (directly or indirectly) return a pointer or a reference to a local object
3322 ##### Reason
3324 To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
3326 ##### Example, bad
3328 After the return from a function its local objects no longer exist:
3330     int* f()
3331     {
3332         int fx = 9;
3333         return &fx;  // BAD
3334     }
3336     void g(int* p)   // looks innocent enough
3337     {
3338         int gx;
3339         cout << "*p == " << *p << '\n';
3340         *p = 999;
3341         cout << "gx == " << gx << '\n';
3342     }
3344     void h()
3345     {
3346         int* p = f();
3347         int z = *p;  // read from abandoned stack frame (bad)
3348         g(p);        // pass pointer to abandoned stack frame to function (bad)
3349     }
3351 Here on one popular implementation I got the output:
3353     *p == 999
3354     gx == 999
3356 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`.
3358 * Imagine what would happen if `fx` and `gx` were of different types.
3359 * Imagine what would happen if `fx` or `gx` was a type with an invariant.
3360 * Imagine what would happen if more that dangling pointer was passed around among a larger set of functions.
3361 * Imagine what a cracker could do with that dangling pointer.
3363 Fortunately, most (all?) modern compilers catch and warn against this simple case.
3365 ##### Note
3367 This applies to references as well:
3369     int& f()
3370     {
3371         int x = 7;
3372         // ...
3373         return x;  // Bad: returns reference to object that is about to be destroyed
3374     }
3376 ##### Note
3378 This applies only to non-`static` local variables.
3379 All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.
3381 ##### Example, bad
3383 Not all examples of leaking a pointer to a local variable are that obvious:
3385     int* glob;       // global variables are bad in so many ways
3387     template<class T>
3388     void steal(T x)
3389     {
3390         glob = x();  // BAD
3391     }
3393     void f()
3394     {
3395         int i = 99;
3396         steal([&] { return &i; });
3397     }
3399     int main()
3400     {
3401         f();
3402         cout << *glob << '\n';
3403     }
3405 Here I managed to read the location abandoned by the call of `f`.
3406 The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways.
3408 ##### Note
3410 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.
3412 ##### Note
3414 Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one;
3415 such examples are handled equivalently to leaks of pointers out of a function.
3417 A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.
3419 **See also**: Another way of getting dangling pointers is [pointer invalidation](#???).
3420 It can be detected/prevented with similar techniques.
3422 ##### Enforcement
3424 * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
3425 * Static analysis can catch many common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)
3427 ### <a name="Rf-return-ref"></a>F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed
3429 ##### Reason
3431 The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary.
3433 **See also**: The return of a reference must not imply transfer of ownership:
3434 [discussion of dangling pointer prevention](#???) and [discussion of ownership](#???).
3436 ##### Example
3438     class Car
3439     {
3440         array<wheel, 4> w;
3441         // ...
3442     public:
3443         wheel& get_wheel(size_t i) { Expects(i < 4); return w[i]; }
3444         // ...
3445     };
3447     void use()
3448     {
3449         Car c;
3450         wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c
3451     }
3453 ##### Enforcement
3455 Flag functions where no `return` expression could yield `nullptr`
3457 ### <a name="Rf-return-ref-ref"></a>F.45: Don't return a `T&&`
3459 ##### Reason
3461 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 ???.
3463 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&&`).
3465 ##### Example, bad
3467 If `F` returns by value, this function returns a reference to a temporary.
3469     template<class F>
3470     auto&& wrapper(F f)
3471     {
3472         log_call(typeid(f)); // or whatever instrumentation
3473         return f();
3474     }
3476 ##### Example, good
3478 Better:
3480     template<class F>
3481     auto wrapper(F f)
3482     {
3483         log_call(typeid(f)); // or whatever instrumentation
3484         return f();
3485     }
3487 ##### Exception
3489 `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 `&&`.
3491 ##### Enforcement
3493 Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
3495 ### <a name="Rf-main"></a>F.46: `int` is the return type for `main()`
3497 ##### Reason
3499 It's a language rule, but violated through "language extensions" so often that it is worth mentioning.
3500 Declaring `main` (the one global `main` of a program) `void` limits portability.
3502 ##### Example
3504         void main() { /* ... */ };  // bad, not C++
3506         int main()
3507         {
3508             std::cout << "This is the way to do it\n";
3509         }
3511 ##### Note
3513 We mention this only because of the persistence of this error in the community.
3515 ##### Enforcement
3517 * The compiler should do it
3518 * If the compiler doesn't do it, let tools flag it
3520 ### <a name="Rf-assignment-op"></a>F.47: Return `T&` from assignment operators
3522 ##### Reason
3524 The convention for operator overloads (especially on value types) is for
3525 `operator=(const T&)` to perform the assignment and then return (non-const)
3526 `*this`.  This ensures consistency with standard library types and follows the
3527 principle of "do as the ints do."
3529 ##### Note
3531 Historically there was some guidance to make the assignment operator return `const T&`.
3532 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.
3534 ##### Example
3536     class Foo
3537     {
3538      public:
3539         ...
3540         Foo& operator=(const Foo& rhs) {
3541           // Copy members.
3542           ...
3543           return *this;
3544         }
3545     };
3547 ##### Enforcement
3549 This should be enforced by tooling by checking the return type (and return
3550 value) of any assignment operator.
3552 ### <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)
3554 ##### Reason
3556 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.
3558 ##### Example
3560     // writing a function that should only take an int or a string
3561     // -- overloading is natural
3562     void f(int);
3563     void f(const string&);
3565     // writing a function object that needs to capture local state and appear
3566     // at statement or expression scope -- a lambda is natural
3567     vector<work> v = lots_of_work();
3568     for (int tasknum = 0; tasknum < max; ++tasknum) {
3569         pool.run([=, &v]{
3570             /*
3571             ...
3572             ... process 1 / max - th of v, the tasknum - th chunk
3573             ...
3574             */
3575         });
3576     }
3577     pool.join();
3579 ##### Exception
3581 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.
3583 ##### Enforcement
3585 * 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.
3587 ### <a name="Rf-default-args"></a>F.51: Where there is a choice, prefer default arguments over overloading
3589 ##### Reason
3591 Default arguments simply provides alternative interfaces to a single implementation.
3592 There is no guarantee that a set of overloaded functions all implement the same semantics.
3593 The use of default arguments can avoid code replication.
3595 ##### Note
3597 There is a choice between using default argument and overloading when the alternatives are from a set of arguments of the same types.
3598 For example:
3600     void print(const string& s, format f = {});
3602 as opposed to
3604     void print(const string& s);  // use default format
3605     void print(const string& s, format f);
3607 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:
3609     void print(const char&);
3610     void print(int);
3611     void print(zstring);
3613 ##### See also
3616 [Default arguments for virtual functions](#Rh-virtual-default-arg)
3618 ##### Enforcement
3620     ???
3622 ### <a name="Rf-reference-capture"></a>F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms
3624 ##### Reason
3626 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.
3628 ##### Discussion
3630 The efficiency consideration is that most types are cheaper to pass by reference than by value.
3632 The correctness consideration is that many calls want to perform side effects on the original object at the call site (see example below). Passing by value prevents this.
3634 ##### Note
3636 Unfortunately, there is no simple way to capture by reference to `const` to get the efficiency for a local call but also prevent side effects.
3638 ##### Example
3640 Here, a large object (a network message) is passed to an iterative algorithm, and is it not efficient or correct to copy the message (which may not be copyable):
3642     std::for_each(begin(sockets), end(sockets), [&message](auto& socket)
3643     {
3644         socket.send(message);
3645     });
3647 ##### Example
3649 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.
3651     void send_packets(buffers& bufs)
3652     {
3653         stage encryptor([] (buffer& b){ encrypt(b); });
3654         stage compressor([&](buffer& b){ compress(b); encryptor.process(b); });
3655         stage decorator([&](buffer& b){ decorate(b); compressor.process(b); });
3656         for (auto& b : bufs) { decorator.process(b); }
3657     }  // automatically blocks waiting for pipeline to finish
3659 ##### Enforcement
3661 Flag a lambda that captures by reference, but is used other than locally within the function scope or passed to a function by reference. (Note: This rule is an approximation, but does flag passing by pointer as those are more likely to be stored by the callee, writing to a heap location accessed via a parameter, returning the lambda, etc. The Lifetime rules will also provide general rules that flag escaping pointers and references including via lambdas.)
3663 ### <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
3665 ##### Reason
3667 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.
3669 ##### Example, bad
3671     int local = 42;
3673     // Want a reference to local.
3674     // Note, that after program exits this scope,
3675     // local no longer exists, therefore
3676     // process() call will have undefined behavior!
3677     thread_pool.queue_work([&]{ process(local); });
3679 ##### Example, good
3681     int local = 42;
3682     // Want a copy of local.
3683     // Since a copy of local is made, it will
3684     // always be available for the call.
3685     thread_pool.queue_work([=]{ process(local); });
3687 ##### Enforcement
3689 * (Simple) Warn when capture-list contains a reference to a locally declared variable
3690 * (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
3692 ### <a name="Rf-this-capture"></a>F.54: If you capture `this`, capture all variables explicitly (no default capture)
3694 ##### Reason
3696 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.
3698 ##### Example
3700     class My_class {
3701         int x = 0;
3702         // ...
3704         void f() {
3705             int i = 0;
3706             // ...
3708             auto lambda = [=]{ use(i, x); };   // BAD: "looks like" copy/value capture
3709             // [&] has identical semantics and copies the this pointer under the current rules
3710             // [=,this] and [&,this] are not much better, and confusing
3712             x = 42;
3713             lambda(); // calls use(42);
3714             x = 43;
3715             lambda(); // calls use(43);
3717             // ...
3719             auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing
3721             // ...
3722         }
3723     };
3725 ##### Note
3727 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.
3729 ##### Enforcement
3731 * Flag any lambda capture-list that specifies a default capture and also captures `this` (whether explicitly or via default capture)
3733 # <a name="S-class"></a>C: Classes and Class Hierarchies
3735 A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces.
3736 Class hierarchies are used to organize related classes into hierarchical structures.
3738 Class rule summary:
3740 * [C.1: Organize related data into structures (`struct`s or `class`es)](#Rc-org)
3741 * [C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently](#Rc-struct)
3742 * [C.3: Represent the distinction between an interface and an implementation using a class](#Rc-interface)
3743 * [C.4: Make a function a member only if it needs direct access to the representation of a class](#Rc-member)
3744 * [C.5: Place helper functions in the same namespace as the class they support](#Rc-helper)
3745 * [C.7: Don't define a class or enum and declare a variable of its type in the same statement](#Rc-standalone)
3746 * [C.8: Use `class` rather than `struct` if any member is non-public](#Rc-class)
3747 * [C.9: Minimize exposure of members](#Rc-private)
3749 Subsections:
3751 * [C.concrete: Concrete types](#SS-concrete)
3752 * [C.ctor: Constructors, assignments, and destructors](#S-ctor)
3753 * [C.con: Containers and other resource handles](#SS-containers)
3754 * [C.lambdas: Function objects and lambdas](#SS-lambdas)
3755 * [C.hier: Class hierarchies (OOP)](#SS-hier)
3756 * [C.over: Overloading and overloaded operators](#SS-overload)
3757 * [C.union: Unions](#SS-union)
3759 ### <a name="Rc-org"></a>C.1: Organize related data into structures (`struct`s or `class`es)
3761 ##### Reason
3763 Ease of comprehension.
3764 If data is related (for fundamental reasons), that fact should be reflected in code.
3766 ##### Example
3768     void draw(int x, int y, int x2, int y2);  // BAD: unnecessary implicit relationships
3769     void draw(Point from, Point to);          // better
3771 ##### Note
3773 A simple class without virtual functions implies no space or time overhead.
3775 ##### Note
3777 From a language perspective `class` and `struct` differ only in the default visibility of their members.
3779 ##### Enforcement
3781 Probably impossible. Maybe a heuristic looking for data items used together is possible.
3783 ### <a name="Rc-struct"></a>C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently
3785 ##### Reason
3787 Readability.
3788 Ease of comprehension.
3789 The use of `class` alerts the programmer to the need for an invariant.
3790 This is a useful convention.
3792 ##### Note
3794 An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.
3795 After the invariant is established (typically by a constructor) every member function can be called for the object.
3796 An invariant can be stated informally (e.g., in a comment) or more formally using `Expects`.
3798 If all data members can vary independently of each other, no invariant is possible.
3800 ##### Example
3802     struct Pair {  // the members can vary independently
3803         string name;
3804         int volume;
3805     };
3807 but:
3809     class Date {
3810     public:
3811         // validate that {yy, mm, dd} is a valid date and initialize
3812         Date(int yy, Month mm, char dd);
3813         // ...
3814     private:
3815         int y;
3816         Month m;
3817         char d;    // day
3818     };
3820 ##### Note
3822 If a class has any `private` data, a user cannot completely initialize an object without the use of a constructor.
3823 Hence, the class definer will provide a constructor and must specify its meaning.
3824 This effectively means the definer need to define an invariant.
3826 * See also [define a class with private data as `class`](#Rc-class).
3827 * See also [Prefer to place the interface first in a class](#Rl-order).
3828 * See also [minimize exposure of members](#Rc-private).
3829 * See also [Avoid `protected` data](#Rh-protected).
3831 ##### Enforcement
3833 Look for `struct`s with all data private and `class`es with public members.
3835 ### <a name="Rc-interface"></a>C.3: Represent the distinction between an interface and an implementation using a class
3837 ##### Reason
3839 An explicit distinction between interface and implementation improves readability and simplifies maintenance.
3841 ##### Example
3843     class Date {
3844         // ... some representation ...
3845     public:
3846         Date();
3847         // validate that {yy, mm, dd} is a valid date and initialize
3848         Date(int yy, Month mm, char dd);
3850         int day() const;
3851         Month month() const;
3852         // ...
3853     };
3855 For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though).
3857 ##### Note
3859 Using a class in this way to represent the distinction between interface and implementation is of course not the only way.
3860 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.
3861 The most important issue is to explicitly distinguish between an interface and its implementation "details."
3862 Ideally, and typically, an interface is far more stable than its implementation(s).
3864 ##### Enforcement
3868 ### <a name="Rc-member"></a>C.4: Make a function a member only if it needs direct access to the representation of a class
3870 ##### Reason
3872 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.
3874 ##### Example
3876     class Date {
3877         // ... relatively small interface ...
3878     };
3880     // helper functions:
3881     Date next_weekday(Date);
3882     bool operator==(Date, Date);
3884 The "helper functions" have no need for direct access to the representation of a `Date`.
3886 ##### Note
3888 This rule becomes even better if C++ gets ["uniform function call"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0251r0.pdf).
3890 ##### Exception
3892 The language requires `virtual` functions to be members, and not all `virtual` functions directly access data.
3893 In particular, members of an abstract class rarely do.
3895 Note [multi-methods](https://parasol.tamu.edu/~yuriys/papers/OMM10.pdf).
3897 ##### Exception
3899 The language requires operators `=`, `()`, `[]`, and `->` to be members.
3901 ###### Exception
3903 An overload set may have some members that do not directly access `private` data:
3905     class Foobar {
3906         void foo(int x)    { /* manipulate private data */ }
3907         void foo(double x) { foo(std::round(x)); }
3908         // ...
3909     private:
3910         // ...
3911     };
3913 Similarly, a set of functions may be designed to be used in a chain:
3915     x.scale(0.5).rotate(45).set_color(Color::red);
3917 Typically, some but not all of such functions directly access `private` data.
3919 ##### Enforcement
3921 * Look for non-`virtual` member functions that do not touch data members directly.
3922 The snag is that many member functions that do not need to touch data members directly do.
3923 * Ignore `virtual` functions.
3924 * Ignore functions that are part of an overload set out of which at least one function accesses `private` members.
3925 * Ignore functions returning `this`.
3927 ### <a name="Rc-helper"></a>C.5: Place helper functions in the same namespace as the class they support
3929 ##### Reason
3931 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.
3932 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.
3934 ##### Example
3936     namespace Chrono { // here we keep time-related services
3938         class Time { /* ... */ };
3939         class Date { /* ... */ };
3941         // helper functions:
3942         bool operator==(Date, Date);
3943         Date next_weekday(Date);
3944         // ...
3945     }
3947 ##### Note
3949 This is especially important for [overloaded operators](#Ro-namespace).
3951 ##### Enforcement
3953 * Flag global functions taking argument types from a single namespace.
3955 ### <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
3957 ##### Reason
3959 Mixing a type definition and the definition of another entity in the same declaration is confusing and unnecessary.
3961 ##### Example; bad
3963     struct Data { /*...*/ } data{ /*...*/ };
3965 ##### Example; good
3967     struct Data { /*...*/ };
3968     Data data{ /*...*/ };
3970 ##### Enforcement
3972 * Flag if the `}` of a class or enumeration definition is not followed by a `;`. The `;` is missing.
3974 ### <a name="Rc-class"></a>C.8: Use `class` rather than `struct` if any member is non-public
3976 ##### Reason
3978 Readability.
3979 To make it clear that something is being hidden/abstracted.
3980 This is a useful convention.
3982 ##### Example, bad
3984     struct Date {
3985         int d, m;
3987         Date(int i, Month m);
3988         // ... lots of functions ...
3989     private:
3990         int y;  // year
3991     };
3993 There is nothing wrong with this code as far as the C++ language rules are concerned,
3994 but nearly everything is wrong from a design perspective.
3995 The private data is hidden far from the public data.
3996 The data is split in different parts of the class declaration.
3997 Different parts of the data have different access.
3998 All of this decreases readability and complicates maintenance.
4000 ##### Note
4002 Prefer to place the interface first in a class [see](#Rl-order).
4004 ##### Enforcement
4006 Flag classes declared with `struct` if there is a `private` or `public` member.
4008 ### <a name="Rc-private"></a>C.9: Minimize exposure of members
4010 ##### Reason
4012 Encapsulation.
4013 Information hiding.
4014 Minimize the chance of untended access.
4015 This simplifies maintenance.
4017 ##### Example
4019     template<typename T, typename U>
4020     struct pair {
4021         T a;
4022         U b;
4023         // ...
4024     };
4026 Whatever we do in the `//`-part, an arbitrary user of a `pair` can arbitrarily and independently change its `a` and `b`.
4027 In a large code base, we cannot easily find which code does what to the members of `pair`.
4028 This may be exactly what we want, but if we want to enforce a relation among members, we need to make them `private`
4029 and enforce that relation (invariant) through constructors and member functions.
4030 For example:
4032     struct Distance {
4033     public:
4034         // ...
4035         double meters() const { return magnitude*unit; }
4036         void set_unit(double u)
4037         {
4038                 // ... check that u is a factor of 10 ...
4039                 // ... change magnitude appropriately ...
4040                 unit = u;
4041         }
4042         // ...
4043     private:
4044         double magnitude;
4045         double unit;    // 1 is meters, 1000 is kilometers, 0.0001 is millimeters, etc.
4046     };
4048 ##### Note
4050 If the set of direct users of a set of variables cannot be easily determined, the type or usage of that set cannot be (easily) changed/improved.
4051 For `public` and `protected` data, that's usually the case.
4053 ##### Example
4055 A class can provide two interfaces to its users.
4056 One for derived classes (`protected`) and one for general users (`public`).
4057 For example, a derived class might be allowed to skip a run-time check because it has already guaranteed correctness:
4059     class Foo {
4060     public:
4061         int bar(int x) { check(x); return do_bar(); }
4062         // ...
4063     protected:
4064         int do_bar(int x); // do some operation on the data
4065         // ...
4066     private:
4067         // ... data ...
4068     };
4070     class Dir : public Foo {
4071         //...
4072         int mem(int x, int y)
4073         {
4074             /* ... do something ... */
4075             return do_bar(x+y); // OK: derived class can bypass check
4076         }
4077     }
4079     void user(Foo& x)
4080     {
4081         int r1 = x.bar(1);      // OK, will check
4082         int r2 = x.do_bar(2);   // error: would bypass check
4083         // ...
4084     }
4086 ##### Note
4088 [`protected` data is a bad idea](#Rh-protected).
4090 ##### Note
4092 Prefer the order `public` members before `protected` members before `private` members [see](#Rl-order).
4094 ##### Enforcement
4096 * [Flag protected data](#Rh-protected).
4097 * Flag mixtures of `public` and private `data`
4099 ## <a name="SS-concrete"></a>C.concrete: Concrete types
4101 One ideal for a class is to be a regular type.
4102 That means roughly "behaves like an `int`." A concrete type is the simplest kind of class.
4103 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.
4104 If a concrete type has both `=` and `==`, `a = b` should result in `a == b` being `true`.
4105 Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
4106 The C++ built-in types are regular, and so are standard-library classes, such as `string`, `vector`, and `map`.
4107 Concrete types are also often referred to as value types to distinguish them from types used as part of a hierarchy.
4109 Concrete type rule summary:
4111 * [C.10: Prefer concrete types over class hierarchies](#Rc-concrete)
4112 * [C.11: Make concrete types regular](#Rc-regular)
4114 ### <a name="Rc-concrete"></a>C.10 Prefer concrete types over class hierarchies
4116 ##### Reason
4118 A concrete type is fundamentally simpler than a hierarchy:
4119 easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.
4120 You need a reason (use cases) for using a hierarchy.
4122 ##### Example
4124     class Point1 {
4125         int x, y;
4126         // ... operations ...
4127         // ... no virtual functions ...
4128     };
4130     class Point2 {
4131         int x, y;
4132         // ... operations, some virtual ...
4133         virtual ~Point2();
4134     };
4136     void use()
4137     {
4138         Point1 p11 {1, 2};   // make an object on the stack
4139         Point1 p12 {p11};    // a copy
4141         auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
4142         auto p22 = p21.clone();                 // make a copy
4143         // ...
4144     }
4146 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.
4147 That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.
4149 ##### Note
4151 Concrete types can be stack allocated and be members of other classes.
4153 ##### Note
4155 The use of indirection is fundamental for run-time polymorphic interfaces.
4156 The allocation/deallocation overhead is not (that's just the most common case).
4157 We can use a base class as the interface of a scoped object of a derived class.
4158 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.
4160 ##### Enforcement
4164 ### <a name="Rc-regular"></a>C.11: Make concrete types regular
4166 ##### Reason
4168 Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
4170 ##### Example
4172     struct Bundle {
4173         string name;
4174         vector<Record> vr;
4175     };
4177     bool operator==(const Bundle& a, const Bundle& b)
4178     {
4179         return a.name == b.name && a.vr == b.vr;
4180     }
4182     Bundle b1 { "my bundle", {r1, r2, r3}};
4183     Bundle b2 = b1;
4184     if (!(b1 == b2)) error("impossible!");
4185     b2.name = "the other bundle";
4186     if (b1 == b2) error("No!");
4188 In particular, if a concrete type has an assignment also give it an equals operator so that `a = b` implies `a == b`.
4190 ##### Enforcement
4194 ## <a name="S-ctor"></a>C.ctor: Constructors, assignments, and destructors
4196 These functions control the lifecycle of objects: creation, copy, move, and destruction.
4197 Define constructors to guarantee and simplify initialization of classes.
4199 These are *default operations*:
4201 * a default constructor: `X()`
4202 * a copy constructor: `X(const X&)`
4203 * a copy assignment: `operator=(const X&)`
4204 * a move constructor: `X(X&&)`
4205 * a move assignment: `operator=(X&&)`
4206 * a destructor: `~X()`
4208 By default, the compiler defines each of these operations if it is used, but the default can be suppressed.
4210 The default operations are a set of related operations that together implement the lifecycle semantics of an object.
4211 By default, C++ treats classes as value-like types, but not all types are value-like.
4213 Set of default operations rules:
4215 * [C.20: If you can avoid defining any default operations, do](#Rc-zero)
4216 * [C.21: If you define or `=delete` any default operation, define or `=delete` them all](#Rc-five)
4217 * [C.22: Make default operations consistent](#Rc-matched)
4219 Destructor rules:
4221 * [C.30: Define a destructor if a class needs an explicit action at object destruction](#Rc-dtor)
4222 * [C.31: All resources acquired by a class must be released by the class's destructor](#Rc-dtor-release)
4223 * [C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning](#Rc-dtor-ptr)
4224 * [C.33: If a class has an owning pointer member, define or `=delete` a destructor](#Rc-dtor-ptr2)
4225 * [C.34: If a class has an owning reference member, define or `=delete` a destructor](#Rc-dtor-ref)
4226 * [C.35: A base class with a virtual function needs a virtual destructor](#Rc-dtor-virtual)
4227 * [C.36: A destructor may not fail](#Rc-dtor-fail)
4228 * [C.37: Make destructors `noexcept`](#Rc-dtor-noexcept)
4230 Constructor rules:
4232 * [C.40: Define a constructor if a class has an invariant](#Rc-ctor)
4233 * [C.41: A constructor should create a fully initialized object](#Rc-complete)
4234 * [C.42: If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
4235 * [C.43: Ensure that a class has a default constructor](#Rc-default0)
4236 * [C.44: Prefer default constructors to be simple and non-throwing](#Rc-default00)
4237 * [C.45: Don't define a default constructor that only initializes data members; use member initializers instead](#Rc-default)
4238 * [C.46: By default, declare single-argument constructors `explicit`](#Rc-explicit)
4239 * [C.47: Define and initialize member variables in the order of member declaration](#Rc-order)
4240 * [C.48: Prefer in-class initializers to member initializers in constructors for constant initializers](#Rc-in-class-initializer)
4241 * [C.49: Prefer initialization to assignment in constructors](#Rc-initialize)
4242 * [C.50: Use a factory function if you need "virtual behavior" during initialization](#Rc-factory)
4243 * [C.51: Use delegating constructors to represent common actions for all constructors of a class](#Rc-delegating)
4244 * [C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization](#Rc-inheriting)
4246 Copy and move rules:
4248 * [C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`](#Rc-copy-assignment)
4249 * [C.61: A copy operation should copy](#Rc-copy-semantic)
4250 * [C.62: Make copy assignment safe for self-assignment](#Rc-copy-self)
4251 * [C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`](#Rc-move-assignment)
4252 * [C.64: A move operation should move and leave its source in a valid state](#Rc-move-semantic)
4253 * [C.65: Make move assignment safe for self-assignment](#Rc-move-self)
4254 * [C.66: Make move operations `noexcept`](#Rc-move-noexcept)
4255 * [C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired](#Rc-copy-virtual)
4257 Other default operations rules:
4259 * [C.80: Use `=default` if you have to be explicit about using the default semantics](#Rc-eqdefault)
4260 * [C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)](#Rc-delete)
4261 * [C.82: Don't call virtual functions in constructors and destructors](#Rc-ctor-virtual)
4262 * [C.83: For value-like types, consider providing a `noexcept` swap function](#Rc-swap)
4263 * [C.84: A `swap` may not fail](#Rc-swap-fail)
4264 * [C.85: Make `swap` `noexcept`](#Rc-swap-noexcept)
4265 * [C.86: Make `==` symmetric with respect of operand types and `noexcept`](#Rc-eq)
4266 * [C.87: Beware of `==` on base classes](#Rc-eq-base)
4267 * [C.89: Make a `hash` `noexcept`](#Rc-hash)
4269 ## <a name="SS-defop"></a>C.defop: Default Operations
4271 By default, the language supplies the default operations with their default semantics.
4272 However, a programmer can disable or replace these defaults.
4274 ### <a name="Rc-zero"></a>C.20: If you can avoid defining default operations, do
4276 ##### Reason
4278 It's the simplest and gives the cleanest semantics.
4280 ##### Example
4282     struct Named_map {
4283     public:
4284         // ... no default operations declared ...
4285     private:
4286         string name;
4287         map<int, int> rep;
4288     };
4290     Named_map nm;        // default construct
4291     Named_map nm2 {nm};  // copy construct
4293 Since `std::map` and `string` have all the special functions, no further work is needed.
4295 ##### Note
4297 This is known as "the rule of zero".
4299 ##### Enforcement
4301 (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
4302 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`.
4304 ### <a name="Rc-five"></a>C.21: If you define or `=delete` any default operation, define or `=delete` them all
4306 ##### Reason
4308 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.
4310 ##### Example, bad
4312     struct M2 {   // bad: incomplete set of default operations
4313     public:
4314         // ...
4315         // ... no copy or move operations ...
4316         ~M2() { delete[] rep; }
4317     private:
4318         pair<int, int>* rep;  // zero-terminated set of pairs
4319     };
4321     void use()
4322     {
4323         M2 x;
4324         M2 y;
4325         // ...
4326         x = y;   // the default assignment
4327         // ...
4328     }
4330 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).
4332 ##### Note
4334 This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor.
4336 ##### Note
4338 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.
4339 If you don't want a default operation, suppress it with `=delete`.
4341 ##### Note
4343 Compilers enforce much of this rule and ideally warn about any violation.
4345 ##### Note
4347 Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
4349 ##### Enforcement
4351 (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions.
4353 ### <a name="Rc-matched"></a>C.22: Make default operations consistent
4355 ##### Reason
4357 The default operations are conceptually a matched set. Their semantics are interrelated.
4358 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.
4360 ##### Example, bad
4362     class Silly {   // BAD: Inconsistent copy operations
4363         class Impl {
4364             // ...
4365         };
4366         shared_ptr<Impl> p;
4367     public:
4368         Silly(const Silly& a) : p{a.p} { *p = *a.p; }   // deep copy
4369         Silly& operator=(const Silly& a) { p = a.p; }   // shallow copy
4370         // ...
4371     };
4373 These operations disagree about copy semantics. This will lead to confusion and bugs.
4375 ##### Enforcement
4377 * (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.
4378 * (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
4379 * (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
4380 * (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
4382 ## <a name="SS-dtor"></a>C.dtor: Destructors
4384 "Does this class need a destructor?" is a surprisingly powerful design question.
4385 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);
4386 that is, its members can take care of themselves as concerns destruction.
4387 If the answer is "yes", much of the design of the class follows (see [the rule of five](#Rc-five)).
4389 ### <a name="Rc-dtor"></a>C.30: Define a destructor if a class needs an explicit action at object destruction
4391 ##### Reason
4393 A destructor is implicitly invoked at the end of an object's lifetime.
4394 If the default destructor is sufficient, use it.
4395 Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.
4397 ##### Example
4399     template<typename A>
4400     struct final_action {   // slightly simplified
4401         A act;
4402         final_action(A a) :act{a} {}
4403         ~final_action() { act(); }
4404     };
4406     template<typename A>
4407     final_action<A> finally(A act)   // deduce action type
4408     {
4409         return final_action<A>{act};
4410     }
4412     void test()
4413     {
4414         auto act = finally([]{ cout << "Exit test\n"; });  // establish exit action
4415         // ...
4416         if (something) return;   // act done here
4417         // ...
4418     } // act done here
4420 The whole purpose of `final_action` is to get a piece of code (usually a lambda) executed upon destruction.
4422 ##### Note
4424 There are two general categories of classes that need a user-defined destructor:
4426 * A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class.
4427 * A class that exists primarily to execute an action upon destruction, such as a tracer or `final_action`.
4429 ##### Example, bad
4431     class Foo {   // bad; use the default destructor
4432     public:
4433         // ...
4434         ~Foo() { s = ""; i = 0; vi.clear(); }  // clean up
4435     private:
4436         string s;
4437         int i;
4438         vector<int> vi;
4439     };
4441 The default destructor does it better, more efficiently, and can't get it wrong.
4443 ##### Note
4445 If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`.
4447 ##### Enforcement
4449 Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.
4451 ### <a name="Rc-dtor-release"></a>C.31: All resources acquired by a class must be released by the class's destructor
4453 ##### Reason
4455 Prevention of resource leaks, especially in error cases.
4457 ##### Note
4459 For resources represented as classes with a complete set of default operations, this happens automatically.
4461 ##### Example
4463     class X {
4464         ifstream f;   // may own a file
4465         // ... no default operations defined or =deleted ...
4466     };
4468 `X`'s `ifstream` implicitly closes any file it may have open upon destruction of its `X`.
4470 ##### Example, bad
4472     class X2 {     // bad
4473         FILE* f;   // may own a file
4474         // ... no default operations defined or =deleted ...
4475     };
4477 `X2` may leak a file handle.
4479 ##### Note
4481 What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail).
4482 If it does nevertheless, we have a problem that has no really good solution.
4483 For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
4484 See [discussion](#Sd-never-fail).
4485 To make the problem worse, many "close/release" operations are not retryable.
4486 Many have tried to solve this problem, but no general solution is known.
4487 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
4489 ##### Note
4491 A class can hold pointers and references to objects that it does not own.
4492 Obviously, such objects should not be `delete`d by the class's destructor.
4493 For example:
4495     Preprocessor pp { /* ... */ };
4496     Parser p { pp, /* ... */ };
4497     Type_checker tc { p, /* ... */ };
4499 Here `p` refers to `pp` but does not own it.
4501 ##### Enforcement
4503 * (Simple) If a class has pointer or reference member variables that are owners
4504   (e.g., deemed owners by using `gsl::owner`), then they should be referenced in its destructor.
4505 * (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership
4506   (e.g., look into the constructors).
4508 ### <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
4510 ##### Reason
4512 There is a lot of code that is non-specific about ownership.
4514 ##### Example
4516     ???
4518 ##### Note
4520 If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`.
4521 This will aid documentation and analysis.
4523 ##### Enforcement
4525 Look at the initialization of raw member pointers and member references and see if an allocation is used.
4527 ### <a name="Rc-dtor-ptr2"></a>C.33: If a class has an owning pointer member, define a destructor
4529 ##### Reason
4531 An owned object must be `deleted` upon destruction of the object that owns it.
4533 ##### Example
4535 A pointer member may represent a resource.
4536 [A `T*` should not do so](#Rr-ptr), but in older code, that's common.
4537 Consider a `T*` a possible owner and therefore suspect.
4539     template<typename T>
4540     class Smart_ptr {
4541         T* p;   // BAD: vague about ownership of *p
4542         // ...
4543     public:
4544         // ... no user-defined default operations ...
4545     };
4547     void use(Smart_ptr<int> p1)
4548     {
4549         // error: p2.p leaked (if not nullptr and not owned by some other code)
4550         auto p2 = p1;
4551     }
4553 Note that if you define a destructor, you must define or delete [all default operations](#Rc-five):
4555     template<typename T>
4556     class Smart_ptr2 {
4557         T* p;   // BAD: vague about ownership of *p
4558         // ...
4559     public:
4560         // ... no user-defined copy operations ...
4561         ~Smart_ptr2() { delete p; }  // p is an owner!
4562     };
4564     void use(Smart_ptr2<int> p1)
4565     {
4566         auto p2 = p1;   // error: double deletion
4567     }
4569 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:
4571     template<typename T>
4572     class Smart_ptr3 {
4573         owner<T*> p;   // OK: explicit about ownership of *p
4574         // ...
4575     public:
4576         // ...
4577         // ... copy and move operations ...
4578         ~Smart_ptr3() { delete p; }
4579     };
4581     void use(Smart_ptr3<int> p1)
4582     {
4583         auto p2 = p1;   // error: double deletion
4584     }
4586 ##### Note
4588 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.
4590 ##### Note
4592 Why not just require all owning pointers to be "smart pointers"?
4593 That would sometimes require non-trivial code changes and may affect ABIs.
4595 ##### Enforcement
4597 * A class with a pointer data member is suspect.
4598 * A class with an `owner<T>` should define its default operations.
4600 ### <a name="Rc-dtor-ref"></a>C.34: If a class has an owning reference member, define a destructor
4602 ##### Reason
4604 A reference member may represent a resource.
4605 It should not do so, but in older code, that's common.
4606 See [pointer members and destructors](#Rc-dtor-ptr).
4607 Also, copying may lead to slicing.
4609 ##### Example, bad
4611     class Handle {  // Very suspect
4612         Shape& s;   // use reference rather than pointer to prevent rebinding
4613                     // BAD: vague about ownership of *p
4614         // ...
4615     public:
4616         Handle(Shape& ss) : s{ss} { /* ... */ }
4617         // ...
4618     };
4620 The problem of whether `Handle` is responsible for the destruction of its `Shape` is the same as for [the pointer case](#Rc-dtor-ptr):
4621 If the `Handle` owns the object referred to by `s` it must have a destructor.
4623 ##### Example
4625     class Handle {        // OK
4626         owner<Shape&> s;  // use reference rather than pointer to prevent rebinding
4627         // ...
4628     public:
4629         Handle(Shape& ss) : s{ss} { /* ... */ }
4630         ~Handle() { delete &s; }
4631         // ...
4632     };
4634 Independently of whether `Handle` owns its `Shape`, we must consider the default copy operations suspect:
4636     // the Handle had better own the Circle or we have a leak
4637     Handle x {*new Circle{p1, 17}};
4639     Handle y {*new Triangle{p1, p2, p3}};
4640     x = y;     // the default assignment will try *x.s = *y.s
4642 That `x = y` is highly suspect.
4643 Assigning a `Triangle` to a `Circle`?
4644 Unless `Shape` has its [copy assignment `=deleted`](#Rc-copy-virtual), only the `Shape` part of `Triangle` is copied into the `Circle`.
4646 ##### Note
4648 Why not just require all owning references to be replaced by "smart pointers"?
4649 Changing from references to smart pointers implies code changes.
4650 We don't (yet) have smart references.
4651 Also, that may affect ABIs.
4653 ##### Enforcement
4655 * A class with a reference data member is suspect.
4656 * A class with an `owner<T>` reference should define its default operations.
4658 ### <a name="Rc-dtor-virtual"></a>C.35: A base class destructor should be either public and virtual, or protected and nonvirtual
4660 ##### Reason
4662 To prevent undefined behavior.
4663 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.
4664 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.
4665 In general, the writer of a base class does not know the appropriate action to be done upon destruction.
4667 ##### Discussion
4669 See [this in the Discussion section](#Sd-dtor).
4671 ##### Example, bad
4673     struct Base {  // BAD: no virtual destructor
4674         virtual void f();
4675     };
4677     struct D : Base {
4678         string s {"a resource needing cleanup"};
4679         ~D() { /* ... do some cleanup ... */ }
4680         // ...
4681     };
4683     void use()
4684     {
4685         unique_ptr<Base> p = make_unique<D>();
4686         // ...
4687     } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
4689 ##### Note
4691 A virtual function defines an interface to derived classes that can be used without looking at the derived classes.
4692 If the interface allows destroying, it should be safe to do so.
4694 ##### Note
4696 A destructor must be nonprivate or it will prevent using the type :
4698     class X {
4699         ~X();   // private destructor
4700         // ...
4701     };
4703     void use()
4704     {
4705         X a;                        // error: cannot destroy
4706         auto p = make_unique<X>();  // error: cannot destroy
4707     }
4709 ##### Exception
4711 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.
4713 ##### Enforcement
4715 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
4717 ### <a name="Rc-dtor-fail"></a>C.36: A destructor may not fail
4719 ##### Reason
4721 In general we do not know how to write error-free code if a destructor should fail.
4722 The standard library requires that all classes it deals with have destructors that do not exit by throwing.
4724 ##### Example
4726     class X {
4727     public:
4728         ~X() noexcept;
4729         // ...
4730     };
4732     X::~X() noexcept
4733     {
4734         // ...
4735         if (cannot_release_a_resource) terminate();
4736         // ...
4737     }
4739 ##### Note
4741 Many have tried to devise a fool-proof scheme for dealing with failure in destructors.
4742 None have succeeded to come up with a general scheme.
4743 This can be a real practical problem: For example, what about a socket that won't close?
4744 The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
4745 See [discussion](#Sd-dtor).
4746 To make the problem worse, many "close/release" operations are not retryable.
4747 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
4749 ##### Note
4751 Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program.
4753 ##### Note
4755 If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow
4756 (maybe even by modifying some global state and hope something will notice and be able to take care of the problem).
4757 Be fully aware that this technique is special-purpose and error-prone.
4758 Consider the "my connection will not close" example.
4759 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.
4760 The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.
4762 ##### Note
4764 If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully
4765 (e.g., by using a different clean-up mechanism from the one that threw an exception).
4767 ##### Enforcement
4769 (Simple) A destructor should be declared `noexcept` if it could throw.
4771 ### <a name="Rc-dtor-noexcept"></a>C.37: Make destructors `noexcept`
4773 ##### Reason
4775  [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.
4777 ##### Note
4779 A destructor (either user-defined or compiler-generated) is implicitly declared `noexcept` (independently of what code is in its body) if all of the members of its class have `noexcept` destructors. By explicitly marking destructors `noexcept`, an author guards against the destructor becoming implicitly `noexcept(false)` through the addition or modification of a class member.
4781 ##### Enforcement
4783 (Simple) A destructor should be declared `noexcept` if it could throw.
4785 ## <a name="SS-ctor"></a>C.ctor: Constructors
4787 A constructor defines how an object is initialized (constructed).
4789 ### <a name="Rc-ctor"></a>C.40: Define a constructor if a class has an invariant
4791 ##### Reason
4793 That's what constructors are for.
4795 ##### Example
4797     class Date {  // a Date represents a valid date
4798                   // in the January 1, 1900 to December 31, 2100 range
4799         Date(int dd, int mm, int yy)
4800             :d{dd}, m{mm}, y{yy}
4801         {
4802             if (!is_valid(d, m, y)) throw Bad_date{};  // enforce invariant
4803         }
4804         // ...
4805     private:
4806         int d, m, y;
4807     };
4809 It is often a good idea to express the invariant as an `Ensures` on the constructor.
4811 ##### Note
4813 A constructor can be used for convenience even if a class does not have an invariant. For example:
4815     struct Rec {
4816         string s;
4817         int i {0};
4818         Rec(const string& ss) : s{ss} {}
4819         Rec(int ii) :i{ii} {}
4820     };
4822     Rec r1 {7};
4823     Rec r2 {"Foo bar"};
4825 ##### Note
4827 The C++11 initializer list rule eliminates the need for many constructors. For example:
4829     struct Rec2{
4830         string s;
4831         int i;
4832         Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {}   // redundant
4833     };
4835     Rec2 r1 {"Foo", 7};
4836     Rec2 r2 {"Bar"};
4838 The `Rec2` constructor is redundant.
4839 Also, the default for `int` would be better done as a [member initializer](#Rc-in-class-initializer).
4841 **See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw).
4843 ##### Enforcement
4845 * Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant)
4847 ### <a name="Rc-complete"></a>C.41: A constructor should create a fully initialized object
4849 ##### Reason
4851 A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
4853 ##### Example, bad
4855     class X1 {
4856         FILE* f;   // call init() before any other function
4857         // ...
4858     public:
4859         X1() {}
4860         void init();   // initialize f
4861         void read();   // read from f
4862         // ...
4863     };
4865     void f()
4866     {
4867         X1 file;
4868         file.read();   // crash or bad read!
4869         // ...
4870         file.init();   // too late
4871         // ...
4872     }
4874 Compilers do not read comments.
4876 ##### Exception
4878 If a valid object cannot conveniently be constructed by a constructor, [use a factory function](#Rc-factory).
4880 ##### Enforcement
4882 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
4883 * (Unknown) If a constructor has an `Ensures` contract, try to see if it holds as a postcondition.
4885 ##### Note
4887 If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release).
4888 The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisition Is Initialization").
4890 ### <a name="Rc-throw"></a>C.42: If a constructor cannot construct a valid object, throw an exception
4892 ##### Reason
4894 Leaving behind an invalid object is asking for trouble.
4896 ##### Example
4898     class X2 {
4899         FILE* f;   // call init() before any other function
4900         // ...
4901     public:
4902         X2(const string& name)
4903             :f{fopen(name.c_str(), "r")}
4904         {
4905             if (f == nullptr) throw runtime_error{"could not open" + name};
4906             // ...
4907         }
4909         void read();      // read from f
4910         // ...
4911     };
4913     void f()
4914     {
4915         X2 file {"Zeno"}; // throws if file isn't open
4916         file.read();      // fine
4917         // ...
4918     }
4920 ##### Example, bad
4922     class X3 {     // bad: the constructor leaves a non-valid object behind
4923         FILE* f;   // call init() before any other function
4924         bool valid;
4925         // ...
4926     public:
4927         X3(const string& name)
4928             :f{fopen(name.c_str(), "r")}, valid{false}
4929         {
4930             if (f) valid = true;
4931             // ...
4932         }
4934         bool is_valid() { return valid; }
4935         void read();   // read from f
4936         // ...
4937     };
4939     void f()
4940     {
4941         X3 file {"Heraclides"};
4942         file.read();   // crash or bad read!
4943         // ...
4944         if (file.is_valid()) {
4945             file.read();
4946             // ...
4947         }
4948         else {
4949             // ... handle error ...
4950         }
4951         // ...
4952     }
4954 ##### Note
4956 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.
4957 Leaving behind an invalid object and relying on users to consistently check an `is_valid()` function before use is tedious, error-prone, and inefficient.
4959 ##### Exception
4961 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.
4962 There the `is_valid()` technique must be used. In such cases, check `is_valid()` consistently and immediately to simulate [RAII](#Rr-raii).
4964 **Alternative**: If you feel tempted to use some "post-constructor initialization" or "two-stage initialization" idiom, try not to do that.
4965 If you really have to, look at [factory functions](#Rc-factory).
4967 ##### Note
4969 One reason people have used `init()` functions rather than doing the initialization work in a constructor has been to avoid code replication.
4970 [Delegating constructors](#Rc-delegating) and [default member initialization](#Rc-in-class-initializer) do that better.
4971 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)
4973 ##### Enforcement
4975 ### <a name="Rc-default0"></a>C.43: Ensure that a class has a default constructor
4977 ##### Reason
4979 Many language and library facilities rely on default constructors to initialize their elements, e.g. `T a[10]` and `std::vector<T> v(10)`.
4981 ##### Example , bad
4983     class Date { // BAD: no default constructor
4984     public:
4985         Date(int dd, int mm, int yyyy);
4986         // ...
4987     };
4989     vector<Date> vd1(1000);   // default Date needed here
4990     vector<Date> vd2(1000, Date{Month::october, 7, 1885});   // alternative
4992 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.
4994 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.
4995 `{0, 0, 0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's `NaN`.
4996 However, most realistic `Date` classes have a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.
4998 ##### Example
5000     class Date {
5001     public:
5002         Date(int dd, int mm, int yyyy);
5003         Date() = default; // See also C.45
5004         // ...
5005     private:
5006         int dd = 1;
5007         int mm = 1;
5008         int yyyy = 1970;
5009         // ...
5010     };
5012     vector<Date> vd1(1000);
5014 ##### Note
5016 A class with members that all have default constructors implicitly gets a default constructor:
5018     struct X {
5019         string s;
5020         vector<int> v;
5021     };
5023     X x; // means X{{}, {}}; that is the empty string and the empty vector
5025 Beware that built-in types are not properly default constructed:
5027     struct X {
5028         string s;
5029         int i;
5030     };
5032     void f()
5033     {
5034         X x;    // x.s is initialized to the empty string; x.i is uninitialized
5036         cout << x.s << ' ' << x.i << '\n';
5037         ++x.i;
5038     }
5040 Statically allocated objects of built-in types are by default initialized to `0`, but local built-in variables are not.
5041 Beware that your compiler may default initialize local built-in variables, whereas an optimized build will not.
5042 Thus, code like the example above may appear to work, but it relies on undefined behavior.
5043 Assuming that you want initialization, an explicit default initialization can help:
5045     struct X {
5046         string s;
5047         int i {};   // default initialize (to 0)
5048     };
5050 ##### Enforcement
5052 * Flag classes without a default constructor
5054 ### <a name="Rc-default00"></a>C.44: Prefer default constructors to be simple and non-throwing
5056 ##### Reason
5058 Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
5060 ##### Example, problematic
5062     template<typename T>
5063     // elem points to space-elem element allocated using new
5064     class Vector0 {
5065     public:
5066         Vector0() :Vector0{0} {}
5067         Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
5068         // ...
5069     private:
5070         own<T*> elem;
5071         T* space;
5072         T* last;
5073     };
5075 This is nice and general, but setting a `Vector0` to empty after an error involves an allocation, which may fail.
5076 Also, having a default `Vector` represented as `{new T[0], 0, 0}` seems wasteful.
5077 For example, `Vector0 v(100)` costs 100 allocations.
5079 ##### Example
5081     template<typename T>
5082     // elem is nullptr or elem points to space-elem element allocated using new
5083     class Vector1 {
5084     public:
5085         // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
5086         Vector1() noexcept {}
5087         Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
5088         // ...
5089     private:
5090         own<T*> elem = nullptr;
5091         T* space = nullptr;
5092         T* last = nullptr;
5093     };
5095 Using `{nullptr, nullptr, nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks.
5096 Setting a `Vector1` to empty after detecting an error is trivial.
5098 ##### Enforcement
5100 * Flag throwing default constructors
5102 ### <a name="Rc-default"></a>C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
5104 ##### Reason
5106 Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
5108 ##### Example, bad
5110     class X1 { // BAD: doesn't use member initializers
5111         string s;
5112         int i;
5113     public:
5114         X1() :s{"default"}, i{1} { }
5115         // ...
5116     };
5118 ##### Example
5120     class X2 {
5121         string s = "default";
5122         int i = 1;
5123     public:
5124         // use compiler-generated default constructor
5125         // ...
5126     };
5128 ##### Enforcement
5130 (Simple) A default constructor should do more than just initialize member variables with constants.
5132 ### <a name="Rc-explicit"></a>C.46: By default, declare single-argument constructors explicit
5134 ##### Reason
5136 To avoid unintended conversions.
5138 ##### Example, bad
5140     class String {
5141         // ...
5142     public:
5143         String(int);   // BAD
5144         // ...
5145     };
5147     String s = 10;   // surprise: string of size 10
5149 ##### Exception
5151 If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`:
5153     class Complex {
5154         // ...
5155     public:
5156         Complex(double d);   // OK: we want a conversion from d to {d, 0}
5157         // ...
5158     };
5160     Complex z = 10.7;   // unsurprising conversion
5162 **See also**: [Discussion of implicit conversions](#Ro-conversion).
5164 ##### Enforcement
5166 (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".
5168 ### <a name="Rc-order"></a>C.47: Define and initialize member variables in the order of member declaration
5170 ##### Reason
5172 To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
5174 ##### Example, bad
5176     class Foo {
5177         int m1;
5178         int m2;
5179     public:
5180         Foo(int x) :m2{x}, m1{++x} { }   // BAD: misleading initializer order
5181         // ...
5182     };
5184     Foo x(1); // surprise: x.m1 == x.m2 == 2
5186 ##### Enforcement
5188 (Simple) A member initializer list should mention the members in the same order they are declared.
5190 **See also**: [Discussion](#Sd-order)
5192 ### <a name="Rc-in-class-initializer"></a>C.48: Prefer in-class initializers to member initializers in constructors for constant initializers
5194 ##### Reason
5196 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.
5198 ##### Example, bad
5200     class X {   // BAD
5201         int i;
5202         string s;
5203         int j;
5204     public:
5205         X() :i{666}, s{"qqq"} { }   // j is uninitialized
5206         X(int ii) :i{ii} {}         // s is "" and j is uninitialized
5207         // ...
5208     };
5210 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.
5212 ##### Example
5214     class X2 {
5215         int i {666};
5216         string s {"qqq"};
5217         int j {0};
5218     public:
5219         X2() = default;        // all members are initialized to their defaults
5220         X2(int ii) :i{ii} {}   // s and j initialized to their defaults
5221         // ...
5222     };
5224 **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:
5226     class X3 {   // BAD: inexplicit, argument passing overhead
5227         int i;
5228         string s;
5229         int j;
5230     public:
5231         X3(int ii = 666, const string& ss = "qqq", int jj = 0)
5232             :i{ii}, s{ss}, j{jj} { }   // all members are initialized to their defaults
5233         // ...
5234     };
5236 ##### Enforcement
5238 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
5239 * (Simple) Default arguments to constructors suggest an in-class initializer may be more appropriate.
5241 ### <a name="Rc-initialize"></a>C.49: Prefer initialization to assignment in constructors
5243 ##### Reason
5245 An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
5247 ##### Example, good
5249     class A {   // Good
5250         string s1;
5251     public:
5252         A() : s1{"Hello, "} { }    // GOOD: directly construct
5253         // ...
5254     };
5256 ##### Example, bad
5258     class B {   // BAD
5259         string s1;
5260     public:
5261         B() { s1 = "Hello, "; }   // BAD: default constructor followed by assignment
5262         // ...
5263     };
5265     class C {   // UGLY, aka very bad
5266         int* p;
5267     public:
5268         C() { cout << *p; p = new int{10}; }   // accidental use before initialized
5269         // ...
5270     };
5272 ### <a name="Rc-factory"></a>C.50: Use a factory function if you need "virtual behavior" during initialization
5274 ##### Reason
5276 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.
5278 ##### Note
5280 The return type of the factory should normally be `unique_ptr` by default; if some uses are shared, the caller can `move` the `unique_ptr` into a `shared_ptr`. However, if the factory author knows that all uses of the returned object will be shared uses, return `shared_ptr` and use `make_shared` in the body to save an allocation.
5282 ##### Example, bad
5284     class B {
5285     public:
5286         B()
5287         {
5288             // ...
5289             f();   // BAD: virtual call in constructor
5290             // ...
5291         }
5293         virtual void f() = 0;
5295         // ...
5296     };
5298 ##### Example
5300     class B {
5301     protected:
5302         B() { /* ... */ }              // create an imperfectly initialized object
5304         virtual void PostInitialize()  // to be called right after construction
5305         {
5306             // ...
5307             f();    // GOOD: virtual dispatch is safe
5308             // ...
5309         }
5311     public:
5312         virtual void f() = 0;
5314         template<class T>
5315         static shared_ptr<T> Create()  // interface for creating shared objects
5316         {
5317             auto p = make_shared<T>();
5318             p->PostInitialize();
5319             return p;
5320         }
5321     };
5323     class D : public B { /* ... */ };  // some derived class
5325     shared_ptr<D> p = D::Create<D>();  // creating a D object
5327 By making the constructor `protected` we avoid an incompletely constructed object escaping into the wild.
5328 By providing the factory function `Create()`, we make construction (on the free store) convenient.
5330 ##### Note
5332 Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.
5334 **See also**: [Discussion](#Sd-factory)
5336 ### <a name="Rc-delegating"></a>C.51: Use delegating constructors to represent common actions for all constructors of a class
5338 ##### Reason
5340 To avoid repetition and accidental differences.
5342 ##### Example, bad
5344     class Date {   // BAD: repetitive
5345         int d;
5346         Month m;
5347         int y;
5348     public:
5349         Date(int ii, Month mm, year yy)
5350             :i{ii}, m{mm}, y{yy}
5351             { if (!valid(i, m, y)) throw Bad_date{}; }
5353         Date(int ii, Month mm)
5354             :i{ii}, m{mm} y{current_year()}
5355             { if (!valid(i, m, y)) throw Bad_date{}; }
5356         // ...
5357     };
5359 The common action gets tedious to write and may accidentally not be common.
5361 ##### Example
5363     class Date2 {
5364         int d;
5365         Month m;
5366         int y;
5367     public:
5368         Date2(int ii, Month mm, year yy)
5369             :i{ii}, m{mm}, y{yy}
5370             { if (!valid(i, m, y)) throw Bad_date{}; }
5372         Date2(int ii, Month mm)
5373             :Date2{ii, mm, current_year()} {}
5374         // ...
5375     };
5377 **See also**: If the "repeated action" is a simple initialization, consider [an in-class member initializer](#Rc-in-class-initializer).
5379 ##### Enforcement
5381 (Moderate) Look for similar constructor bodies.
5383 ### <a name="Rc-inheriting"></a>C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization
5385 ##### Reason
5387 If you need those constructors for a derived class, re-implementing them is tedious and error prone.
5389 ##### Example
5391 `std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them:
5393     class Rec {
5394         // ... data and lots of nice constructors ...
5395     };
5397     class Oper : public Rec {
5398         using Rec::Rec;
5399         // ... no data members ...
5400         // ... lots of nice utility functions ...
5401     };
5403 ##### Example, bad
5405     struct Rec2 : public Rec {
5406         int x;
5407         using Rec::Rec;
5408     };
5410     Rec2 r {"foo", 7};
5411     int val = r.x;   // uninitialized
5413 ##### Enforcement
5415 Make sure that every member of the derived class is initialized.
5417 ## <a name="SS-copy"></a>C.copy: Copy and move
5419 Value types should generally be copyable, but interfaces in a class hierarchy should not.
5420 Resource handles may or may not be copyable.
5421 Types can be defined to move for logical as well as performance reasons.
5423 ### <a name="Rc-copy-assignment"></a>C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`
5425 ##### Reason
5427 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)).
5429 ##### Example
5431     class Foo {
5432     public:
5433         Foo& operator=(const Foo& x)
5434         {
5435             // GOOD: no need to check for self-assignment (other than performance)
5436             auto tmp = x;
5437             std::swap(*this, tmp);
5438             return *this;
5439         }
5440         // ...
5441     };
5443     Foo a;
5444     Foo b;
5445     Foo f();
5447     a = b;    // assign lvalue: copy
5448     a = f();  // assign rvalue: potentially move
5450 ##### Note
5452 The `swap` implementation technique offers the [strong guarantee](???).
5454 ##### Example
5456 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:
5458     template<typename T>
5459     class Vector {
5460     public:
5461         Vector& operator=(const Vector&);
5462         // ...
5463     private:
5464         T* elem;
5465         int sz;
5466     };
5468     Vector& Vector::operator=(const Vector& a)
5469     {
5470         if (a.sz > sz) {
5471             // ... use the swap technique, it can't be bettered ...
5472             return *this
5473         }
5474         // ... copy sz elements from *a.elem to elem ...
5475         if (a.sz < sz) {
5476             // ... destroy the surplus elements in *this* and adjust size ...
5477         }
5478         return *this;
5479     }
5481 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).
5483 **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&)`.
5484 See [copy constructor vs. `clone()`](#Rc-copy-virtual).
5486 ##### Enforcement
5488 * (Simple) An assignment operator should not be virtual. Here be dragons!
5489 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
5490 * (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators.
5491   Look at the destructor to determine if the type has pointer semantics or value semantics.
5493 ### <a name="Rc-copy-semantic"></a>C.61: A copy operation should copy
5495 ##### Reason
5497 That is the generally assumed semantics. After `x = y`, we should have `x == y`.
5498 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).
5500 ##### Example
5502     class X {   // OK: value semantics
5503     public:
5504         X();
5505         X(const X&);     // copy X
5506         void modify();   // change the value of X
5507         // ...
5508         ~X() { delete[] p; }
5509     private:
5510         T* p;
5511         int sz;
5512     };
5514     bool operator==(const X& a, const X& b)
5515     {
5516         return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
5517     }
5519     X::X(const X& a)
5520         :p{new T[a.sz]}, sz{a.sz}
5521     {
5522         copy(a.p, a.p + sz, a.p);
5523     }
5525     X x;
5526     X y = x;
5527     if (x != y) throw Bad{};
5528     x.modify();
5529     if (x == y) throw Bad{};   // assume value semantics
5531 ##### Example
5533     class X2 {  // OK: pointer semantics
5534     public:
5535         X2();
5536         X2(const X&) = default; // shallow copy
5537         ~X2() = default;
5538         void modify();          // change the value of X
5539         // ...
5540     private:
5541         T* p;
5542         int sz;
5543     };
5545     bool operator==(const X2& a, const X2& b)
5546     {
5547         return a.sz == b.sz && a.p == b.p;
5548     }
5550     X2 x;
5551     X2 y = x;
5552     if (x != y) throw Bad{};
5553     x.modify();
5554     if (x != y) throw Bad{};  // assume pointer semantics
5556 ##### Note
5558 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.
5560 ##### Enforcement
5562 (Not enforceable)
5564 ### <a name="Rc-copy-self"></a>C.62: Make copy assignment safe for self-assignment
5566 ##### Reason
5568 If `x = x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks).
5570 ##### Example
5572 The standard-library containers handle self-assignment elegantly and efficiently:
5574     std::vector<int> v = {3, 1, 4, 1, 5, 9};
5575     v = v;
5576     // the value of v is still {3, 1, 4, 1, 5, 9}
5578 ##### Note
5580 The default assignment generated from members that handle self-assignment correctly handles self-assignment.
5582     struct Bar {
5583         vector<pair<int, int>> v;
5584         map<string, int> m;
5585         string s;
5586     };
5588     Bar b;
5589     // ...
5590     b = b;   // correct and efficient
5592 ##### Note
5594 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)).
5596     class Foo {
5597         string s;
5598         int i;
5599     public:
5600         Foo& operator=(const Foo& a);
5601         // ...
5602     };
5604     Foo& Foo::operator=(const Foo& a)   // OK, but there is a cost
5605     {
5606         if (this == &a) return *this;
5607         s = a.s;
5608         i = a.i;
5609         return *this;
5610     }
5612 This is obviously safe and apparently efficient.
5613 However, what if we do one self-assignment per million assignments?
5614 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).
5615 Consider:
5617     Foo& Foo::operator=(const Foo& a)   // simpler, and probably much better
5618     {
5619         s = a.s;
5620         i = a.i;
5621         return *this;
5622     }
5624 `std::string` is safe for self-assignment and so are `int`. All the cost is carried by the (rare) case of self-assignment.
5626 ##### Enforcement
5628 (Simple) Assignment operators should not contain the pattern `if (this == &a) return *this;` ???
5630 ### <a name="Rc-move-assignment"></a>C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const &`
5632 ##### Reason
5634 It is simple and efficient.
5636 **See**: [The rule for copy-assignment](#Rc-copy-assignment).
5638 ##### Enforcement
5640 Equivalent to what is done for [copy-assignment](#Rc-copy-assignment).
5642 * (Simple) An assignment operator should not be virtual. Here be dragons!
5643 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
5644 * (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.
5646 ### <a name="Rc-move-semantic"></a>C.64: A move operation should move and leave its source in a valid state
5648 ##### Reason
5650 That is the generally assumed semantics.
5651 After `y = std::move(x)` the value of `y` should be the value `x` had and `x` should be in a valid state.
5653 ##### Example
5655     template<typename T>
5656     class X {   // OK: value semantics
5657     public:
5658         X();
5659         X(X&& a);          // move X
5660         void modify();     // change the value of X
5661         // ...
5662         ~X() { delete[] p; }
5663     private:
5664         T* p;
5665         int sz;
5666     };
5669     X::X(X&& a)
5670         :p{a.p}, sz{a.sz}  // steal representation
5671     {
5672         a.p = nullptr;     // set to "empty"
5673         a.sz = 0;
5674     }
5676     void use()
5677     {
5678         X x{};
5679         // ...
5680         X y = std::move(x);
5681         x = X{};   // OK
5682     } // OK: x can be destroyed
5684 ##### Note
5686 Ideally, that moved-from should be the default value of the type.
5687 Ensure that unless there is an exceptionally good reason not to.
5688 However, not all types have a default value and for some types establishing the default value can be expensive.
5689 The standard requires only that the moved-from object can be destroyed.
5690 Often, we can easily and cheaply do better: The standard library assumes that it it possible to assign to a moved-from object.
5691 Always leave the moved-from object in some (necessarily specified) valid state.
5693 ##### Note
5695 Unless there is an exceptionally strong reason not to, make `x = std::move(y); y = z;` work with the conventional semantics.
5697 ##### Enforcement
5699 (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.
5701 ### <a name="Rc-move-self"></a>C.65: Make move assignment safe for self-assignment
5703 ##### Reason
5705 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.
5707 ##### Example
5709     class Foo {
5710         string s;
5711         int i;
5712     public:
5713         Foo& operator=(Foo&& a);
5714         // ...
5715     };
5717     Foo& Foo::operator=(Foo&& a)       // OK, but there is a cost
5718     {
5719         if (this == &a) return *this;  // this line is redundant
5720         s = std::move(a.s);
5721         i = a.i;
5722         return *this;
5723     }
5725 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.
5727 ##### Note
5729 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).
5731 ##### Note
5733 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.
5735 ##### Example
5737 Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment):
5739     // move from other.ptr to this->ptr
5740     T* temp = other.ptr;
5741     other.ptr = nullptr;
5742     delete ptr;
5743     ptr = temp;
5745 ##### Enforcement
5747 * (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`.
5748 * (Not enforceable) Look at the use of standard-library container types (incl. `string`) and consider them safe for ordinary (not life-critical) uses.
5750 ### <a name="Rc-move-noexcept"></a>C.66: Make move operations `noexcept`
5752 ##### Reason
5754 A throwing move violates most people's reasonably assumptions.
5755 A non-throwing move will be used more efficiently by standard-library and language facilities.
5757 ##### Example
5759     template<typename T>
5760     class Vector {
5761         // ...
5762         Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.sz = 0; a.elem = nullptr; }
5763         Vector& operator=(Vector&& a) noexcept { elem = a.elem; sz = a.sz; a.sz = 0; a.elem = nullptr; }
5764         // ...
5765     public:
5766         T* elem;
5767         int sz;
5768     };
5770 These copy operations do not throw.
5772 ##### Example, bad
5774     template<typename T>
5775     class Vector2 {
5776         // ...
5777         Vector2(Vector2&& a) { *this = a; }             // just use the copy
5778         Vector2& operator=(Vector2&& a) { *this = a; }  // just use the copy
5779         // ...
5780     public:
5781         T* elem;
5782         int sz;
5783     };
5785 This `Vector2` is not just inefficient, but since a vector copy requires allocation, it can throw.
5787 ##### Enforcement
5789 (Simple) A move operation should be marked `noexcept`.
5791 ### <a name="Rc-copy-virtual"></a>C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired
5793 ##### Reason
5795 To prevent slicing, because the normal copy operations will copy only the base portion of a derived object.
5797 ##### Example, bad
5799     class B { // BAD: base class doesn't suppress copying
5800         int data;
5801         // ... nothing about copy operations, so uses default ...
5802     };
5804     class D : public B {
5805         string more_data; // add a data member
5806         // ...
5807     };
5809     auto d = make_unique<D>();
5811     // oops, slices the object; gets only d.data but drops d.more_data
5812     auto b = make_unique<B>(d);
5814 ##### Example
5816     class B { // GOOD: base class suppresses copying
5817         B(const B&) = delete;
5818         B& operator=(const B&) = delete;
5819         virtual unique_ptr<B> clone() { return /* B object */; }
5820         // ...
5821     };
5823     class D : public B {
5824         string more_data; // add a data member
5825         unique_ptr<B> clone() override { return /* D object */; }
5826         // ...
5827     };
5829     auto d = make_unique<D>();
5830     auto b = d.clone(); // ok, deep clone
5832 ##### Note
5834 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.
5836 ##### Exception
5838 If you need covariant return types, return an `owner<derived*>`. See [C.130](#Rh-copy).
5840 ##### Enforcement
5842 A class with any virtual function should not have a copy constructor or copy assignment operator (compiler-generated or handwritten).
5844 ## C.other: Other default operation rules
5846 In addition to the operations for which the language offer default implementations,
5847 there are a few operations that are so foundational that it rules for their definition are needed:
5848 comparisons, `swap`, and `hash`.
5850 ### <a name="Rc-eqdefault"></a>C.80: Use `=default` if you have to be explicit about using the default semantics
5852 ##### Reason
5854 The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.
5856 ##### Example
5858     class Tracer {
5859         string message;
5860     public:
5861         Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
5862         ~Tracer() { cerr << "exiting " << message << '\n'; }
5864         Tracer(const Tracer&) = default;
5865         Tracer& operator=(const Tracer&) = default;
5866         Tracer(Tracer&&) = default;
5867         Tracer& operator=(Tracer&&) = default;
5868     };
5870 Because we defined the destructor, we must define the copy and move operations. The `= default` is the best and simplest way of doing that.
5872 ##### Example, bad
5874     class Tracer2 {
5875         string message;
5876     public:
5877         Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
5878         ~Tracer2() { cerr << "exiting " << message << '\n'; }
5880         Tracer2(const Tracer2& a) : message{a.message} {}
5881         Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
5882         Tracer2(Tracer2&& a) :message{a.message} {}
5883         Tracer2& operator=(Tracer2&& a) { message = a.message; return *this; }
5884     };
5886 Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.
5888 ##### Enforcement
5890 (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
5892 ### <a name="Rc-delete"></a>C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)
5894 ##### Reason
5896 In a few cases, a default operation is not desirable.
5898 ##### Example
5900     class Immortal {
5901     public:
5902         ~Immortal() = delete;   // do not allow destruction
5903         // ...
5904     };
5906     void use()
5907     {
5908         Immortal ugh;   // error: ugh cannot be destroyed
5909         Immortal* p = new Immortal{};
5910         delete p;       // error: cannot destroy *p
5911     }
5913 ##### Example
5915 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:
5917     template <class T, class D = default_delete<T>> class unique_ptr {
5918     public:
5919         // ...
5920         constexpr unique_ptr() noexcept;
5921         explicit unique_ptr(pointer p) noexcept;
5922         // ...
5923         unique_ptr(unique_ptr&& u) noexcept;   // move constructor
5924         // ...
5925         unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
5926         // ...
5927     };
5929     unique_ptr<int> make();   // make "something" and return it by moving
5931     void f()
5932     {
5933         unique_ptr<int> pi {};
5934         auto pi2 {pi};      // error: no move constructor from lvalue
5935         auto pi3 {make()};  // OK, move: the result of make() is an rvalue
5936     }
5938 ##### Enforcement
5940 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.
5942 ### <a name="Rc-ctor-virtual"></a>C.82: Don't call virtual functions in constructors and destructors
5944 ##### Reason
5946 The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class.
5947 This can be most confusing.
5948 Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.
5950 ##### Example, bad
5952     class Base {
5953     public:
5954         virtual void f() = 0;   // not implemented
5955         virtual void g();       // implemented with Base version
5956         virtual void h();       // implemented with Base version
5957     };
5959     class Derived : public Base {
5960     public:
5961         void g() override;   // provide Derived implementation
5962         void h() final;      // provide Derived implementation
5964         Derived()
5965         {
5966             // BAD: attempt to call an unimplemented virtual function
5967             f();
5969             // BAD: will call Derived::g, not dispatch further virtually
5970             g();
5972             // GOOD: explicitly state intent to call only the visible version
5973             Derived::g();
5975             // ok, no qualification needed, h is final
5976             h();
5977         }
5978     };
5980 Note that calling a specific explicitly qualified function is not a virtual call even if the function is `virtual`.
5982 **See also** [factory functions](#Rc-factory) for how to achieve the effect of a call to a derived class function without risking undefined behavior.
5984 ##### Note
5986 There is nothing inherently wrong with calling virtual functions from constructors and destructors.
5987 The semantics of such calls is type safe.
5988 However, experience shows that such calls are rarely needed, easily confuse maintainers, and become a source of errors when used by novices.
5990 ##### Enforcement
5992 * Flag calls of virtual functions from constructors and destructors.
5994 ### <a name="Rc-swap"></a>C.83: For value-like types, consider providing a `noexcept` swap function
5996 ##### Reason
5998 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).
6000 ##### Example, good
6002     class Foo {
6003         // ...
6004     public:
6005         void swap(Foo& rhs) noexcept
6006         {
6007             m1.swap(rhs.m1);
6008             std::swap(m2, rhs.m2);
6009         }
6010     private:
6011         Bar m1;
6012         int m2;
6013     };
6015 Providing a nonmember `swap` function in the same namespace as your type for callers' convenience.
6017     void swap(Foo& a, Foo& b)
6018     {
6019         a.swap(b);
6020     }
6022 ##### Enforcement
6024 * (Simple) A class without virtual functions should have a `swap` member function declared.
6025 * (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6027 ### <a name="Rc-swap-fail"></a>C.84: A `swap` function may not fail
6029 ##### Reason
6031  `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.
6033 ##### Example, bad
6035     void swap(My_vector& x, My_vector& y)
6036     {
6037         auto tmp = x;   // copy elements
6038         x = y;
6039         y = tmp;
6040     }
6042 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.
6044 ##### Enforcement
6046 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6048 ### <a name="Rc-swap-noexcept"></a>C.85: Make `swap` `noexcept`
6050 ##### Reason
6052  [A `swap` may not fail](#Rc-swap-fail).
6053 If a `swap` tries to exit with an exception, it's a bad design error and the program had better terminate.
6055 ##### Enforcement
6057 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
6059 ### <a name="Rc-eq"></a>C.86: Make `==` symmetric with respect to operand types and `noexcept`
6061 ##### Reason
6063 Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.
6064 `==` is a fundamental operations and programmers should be able to use it without fear of failure.
6066 ##### Example
6068     class X {
6069         string name;
6070         int number;
6071     };
6073     bool operator==(const X& a, const X& b) noexcept {
6074         return a.name == b.name && a.number == b.number;
6075     }
6077 ##### Example, bad
6079     class B {
6080         string name;
6081         int number;
6082         bool operator==(const B& a) const {
6083             return name == a.name && number == a.number;
6084         }
6085         // ...
6086     };
6088 `B`'s comparison accepts conversions for its second operand, but not its first.
6090 ##### Note
6092 If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw.
6093 The alternative is to make two failure states compare equal and any valid state compare false against the failure state.
6095 #### Note
6097 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6099 ##### Enforcement
6101 * Flag an `operator==()` for which the argument types differ; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6102 * Flag member `operator==()`s; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6104 ### <a name="Rc-eq-base"></a>C.87: Beware of `==` on base classes
6106 ##### Reason
6108 It is really hard to write a foolproof and useful `==` for a hierarchy.
6110 ##### Example, bad
6112     class B {
6113         string name;
6114         int number;
6115         virtual bool operator==(const B& a) const
6116         {
6117              return name == a.name && number == a.number;
6118         }
6119         // ...
6120     };
6122 `B`'s comparison accepts conversions for its second operand, but not its first.
6124     class D :B {
6125         char character;
6126         virtual bool operator==(const D& a) const
6127         {
6128             return name == a.name && number == a.number && character == a.character;
6129         }
6130         // ...
6131     };
6133     B b = ...
6134     D d = ...
6135     b == d;    // compares name and number, ignores d's character
6136     d == b;    // error: no == defined
6137     D d2;
6138     d == d2;   // compares name, number, and character
6139     B& b2 = d2;
6140     b2 == d;   // compares name and number, ignores d2's and d's character
6142 Of course there are ways of making `==` work in a hierarchy, but the naive approaches do not scale
6144 #### Note
6146 This rule applies to all the usual comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6148 ##### Enforcement
6150 * Flag a virtual `operator==()`; same for other comparison operators: `!=`, `<`, `<=`, `>`, and `>=`.
6152 ### <a name="Rc-hash"></a>C.89: Make a `hash` `noexcept`
6154 ##### Reason
6156 Users of hashed containers use hash indirectly and don't expect simple access to throw.
6157 It's a standard-library requirement.
6159 ##### Example, bad
6161     template<>
6162     struct hash<My_type> {  // thoroughly bad hash specialization
6163         using result_type = size_t;
6164         using argument_type = My_type;
6166         size_t operator() (const My_type & x) const
6167         {
6168             size_t xs = x.s.size();
6169             if (xs < 4) throw Bad_My_type{};    // "Nobody expects the Spanish inquisition!"
6170             return hash<size_t>()(x.s.size()) ^ trim(x.s);
6171         }
6172     };
6174     int main()
6175     {
6176         unordered_map<My_type, int> m;
6177         My_type mt{ "asdfg" };
6178         m[mt] = 7;
6179         cout << m[My_type{ "asdfg" }] << '\n';
6180     }
6182 If you have to define a `hash` specialization, try simply to let it combine standard-library `hash` specializations with `^` (xor).
6183 That tends to work better than "cleverness" for non-specialists.
6185 ##### Enforcement
6187 * Flag throwing `hash`es.
6189 ## <a name="SS-containers"></a>C.con: Containers and other resource handles
6191 A container is an object holding a sequence of objects of some type; `std::vector` is the archetypical container.
6192 A resource handle is a class that owns a resource; `std::vector` is the typical resource handle; its resource is its sequence of elements.
6194 Summary of container rules:
6196 * [C.100: Follow the STL when defining a container](#Rcon-stl)
6197 * [C.101: Give a container value semantics](#Rcon-val)
6198 * [C.102: Give a container move operations](#Rcon-move)
6199 * [C.103: Give a container an initializer list constructor](#Rcon-init)
6200 * [C.104: Give a container a default constructor that sets it to empty](#Rcon-empty)
6201 * [C.105: Give a constructor and `Extent` constructor](#Rcon-val)
6202 * ???
6203 * [C.109: If a resource handle has pointer semantics, provide `*` and `->`](#rcon-ptr)
6205 **See also**: [Resources](#S-resource)
6207 ## <a name="SS-lambdas"></a>C.lambdas: Function objects and lambdas
6209 A function object is an object supplying an overloaded `()` so that you can call it.
6210 A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object.
6211 Function objects should be cheap to copy (and therefore [passed by value](#Rf-in)).
6213 Summary:
6215 * [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)
6216 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
6217 * [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)
6218 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
6220 ## <a name="SS-hier"></a>C.hier: Class hierarchies (OOP)
6222 A class hierarchy is constructed to represent a set of hierarchically organized concepts (only).
6223 Typically base classes act as interfaces.
6224 There are two major uses for hierarchies, often named implementation inheritance and interface inheritance.
6226 Class hierarchy rule summary:
6228 * [C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)](#Rh-domain)
6229 * [C.121: If a base class is used as an interface, make it a pure abstract class](#Rh-abstract)
6230 * [C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed](#Rh-separation)
6232 Designing rules for classes in a hierarchy summary:
6234 * [C.126: An abstract class typically doesn't need a constructor](#Rh-abstract-ctor)
6235 * [C.127: A class with a virtual function should have a virtual or protected destructor](#Rh-dtor)
6236 * [C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`](#Rh-override)
6237 * [C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance](#Rh-kind)
6238 * [C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead](#Rh-copy)
6239 * [C.131: Avoid trivial getters and setters](#Rh-get)
6240 * [C.132: Don't make a function `virtual` without reason](#Rh-virtual)
6241 * [C.133: Avoid `protected` data](#Rh-protected)
6242 * [C.134: Ensure all non-`const` data members have the same access level](#Rh-public)
6243 * [C.135: Use multiple inheritance to represent multiple distinct interfaces](#Rh-mi-interface)
6244 * [C.136: Use multiple inheritance to represent the union of implementation attributes](#Rh-mi-implementation)
6245 * [C.137: Use `virtual` bases to avoid overly general base classes](#Rh-vbase)
6246 * [C.138: Create an overload set for a derived class and its bases with `using`](#Rh-using)
6247 * [C.139: Use `final` sparingly](#Rh-final)
6248 * [C.140: Do not provide different default arguments for a virtual function and an overrider](#Rh-virtual-default-arg)
6250 Accessing objects in a hierarchy rule summary:
6252 * [C.145: Access polymorphic objects through pointers and references](#Rh-poly)
6253 * [C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable](#Rh-dynamic_cast)
6254 * [C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error](#Rh-ptr-cast)
6255 * [C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative](#Rh-ref-cast)
6256 * [C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`](#Rh-smart)
6257 * [C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s](#Rh-make_unique)
6258 * [C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s](#Rh-make_shared)
6259 * [C.152: Never assign a pointer to an array of derived class objects to a pointer to its base](#Rh-array)
6261 ### <a name="Rh-domain"></a>C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)
6263 ##### Reason
6265 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.
6267 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.
6269 ##### Example
6271     class DrawableUIElement {
6272     public:
6273         virtual void render() const = 0;
6274         // ...
6275     };
6277     class AbstractButton : public DrawableUIElement {
6278     public:
6279         virtual void onClick() = 0;
6280         // ...
6281     };
6283     class PushButton : public AbstractButton {
6284         virtual void render() const override;
6285         virtual void onClick() override;
6286         // ...
6287     };
6289     class Checkbox : public AbstractButton {
6290     // ...
6291     };
6293 ##### Example, bad
6295 Do *not* represent non-hierarchical domain concepts as class hierarchies.
6297     template<typename T>
6298     class Container {
6299     public:
6300         // list operations:
6301         virtual T& get() = 0;
6302         virtual void put(T&) = 0;
6303         virtual void insert(Position) = 0;
6304         // ...
6305         // vector operations:
6306         virtual T& operator[](int) = 0;
6307         virtual void sort() = 0;
6308         // ...
6309         // tree operations:
6310         virtual void balance() = 0;
6311         // ...
6312     };
6314 Here most overriding classes cannot implement most of the functions required in the interface well.
6315 Thus the base class becomes an implementation burden.
6316 Furthermore, the user of `Container` cannot rely on the member functions actually performing a meaningful operations reasonably efficiently;
6317 it may throw an exception instead.
6318 Thus users have to resort to run-time checking and/or
6319 not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a `dynamic_cast`).
6321 ##### Enforcement
6323 * Look for classes with lots of members that do nothing but throw.
6324 * 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`.
6326 ### <a name="Rh-abstract"></a>C.121: If a base class is used as an interface, make it a pure abstract class
6328 ##### Reason
6330 A class is more stable (less brittle) if it does not contain data.
6331 Interfaces should normally be composed entirely of public pure virtual functions and a default/empty virtual destructor.
6333 ##### Example
6335     class My_interface {
6336     public:
6337         // ...only pure virtual functions here ...
6338         virtual ~My_interface() {}   // or =default
6339     };
6341 ##### Example, bad
6343     class Goof {
6344     public:
6345         // ...only pure virtual functions here ...
6346         // no virtual destructor
6347     };
6349     class Derived : public Goof {
6350         string s;
6351         // ...
6352     };
6354     void use()
6355     {
6356         unique_ptr<Goof> p {new Derived{"here we go"}};
6357         f(p.get()); // use Derived through the Goof interface
6358         g(p.get()); // use Derived through the Goof interface
6359     } // leak
6361 The `Derived` is `delete`d through its `Goof` interface, so its `string` is leaked.
6362 Give `Goof` a virtual destructor and all is well.
6365 ##### Enforcement
6367 * Warn on any class that contains data members and also has an overridable (non-`final`) virtual function.
6369 ### <a name="Rh-separation"></a>C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed
6371 ##### Reason
6373 Such as on an ABI (link) boundary.
6375 ##### Example
6377     struct Device {
6378         virtual void write(span<const char> outbuf) = 0;
6379         virtual void read(span<char> inbuf) = 0;
6380     };
6382     class D1 : public Device {
6383         // ... data ...
6385         void write(span<const char> outbuf) override;
6386         void read(span<char> inbuf) override;
6387     };
6389     class D2 : public Device {
6390         // ... different data ...
6392         void write(span<const char> outbuf) override;
6393         void read(span<char> inbuf) override;
6394     };
6396 A user can now use `D1`s and `D2`s interchangeably through the interface provided by `Device`.
6397 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`.
6399 ##### Enforcement
6401     ???
6403 ## C.hierclass: Designing classes in a hierarchy:
6405 ### <a name="Rh-abstract-ctor"></a>C.126: An abstract class typically doesn't need a constructor
6407 ##### Reason
6409 An abstract class typically does not have any data for a constructor to initialize.
6411 ##### Example
6413     ???
6415 ##### Exception
6417 * A base class constructor that does work, such as registering an object somewhere, may need a constructor.
6418 * In extremely rare cases, you might find it reasonable for an abstract class to have a bit of data shared by all derived classes
6419   (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.
6421 ##### Enforcement
6423 Flag abstract classes with constructors.
6425 ### <a name="Rh-dtor"></a>C.127: A class with a virtual function should have a virtual or protected destructor
6427 ##### Reason
6429 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).
6431 ##### Example, bad
6433     struct B {
6434         virtual int f() = 0;
6435         // ... no user-written destructor, defaults to public nonvirtual ...
6436     };
6438     // bad: derived from a class without a virtual destructor
6439     struct D : B {
6440         string s {"default"};
6441     };
6443     void use()
6444     {
6445         unique_ptr<B> p = make_unique<D>();
6446         // ...
6447     } // undefined behavior. May call B::~B only and leak the string
6449 ##### Note
6451 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`.
6453 ##### Enforcement
6455 * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
6456 * Flag `delete` of a class with a virtual function but no virtual destructor.
6458 ### <a name="Rh-override"></a>C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final`
6460 ##### Reason
6462 Readability.
6463 Detection of mistakes.
6464 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.
6466 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`, one should avoid declaring derived class destructors  `virtual` or `override`. Some code base and tools might insist on `override` for destructors, but that is not the recommendation of these guidelines.
6468 ##### Example, bad
6470     struct B {
6471         void f1(int);
6472         virtual void f2(int) const;
6473         virtual void f3(int);
6474         // ...
6475     };
6477     struct D : B {
6478         void f1(int);        // bad (hope for a warning): D::f1() hides B::f1()
6479         void f2(int) const;  // bad (but conventional and valid): no explicit override
6480         void f3(double);     // bad (hope for a warning): D::f3() hides B::f3()
6481         // ...
6482     };
6484     struct Better : B {
6485         void f1(int) override;        // error (caught): D::f1() hides B::f1()
6486         void f2(int) const override;
6487         void f3(double) override;     // error (caught): D::f3() hides B::f3()
6488         // ...
6489     };
6491 ##### Enforcement
6493 * Compare names in base and derived classes and flag uses of the same name that does not override.
6494 * Flag overrides with neither `override` nor `final`.
6495 * Flag function declarations that use more than one of `virtual`, `override`, and `final`.
6497 ### <a name="Rh-kind"></a>C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance
6499 ##### Reason
6501 Implementation details in an interface makes the interface brittle;
6502 that is, makes its users vulnerable to having to recompile after changes in the implementation.
6503 Data in a base class increases the complexity of implementing the base and can lead to replication of code.
6505 ##### Note
6507 Definition:
6509 * interface inheritance is the use of inheritance to separate users from implementations,
6510 in particular to allow derived classes to be added and changed without affecting the users of base classes.
6511 * implementation inheritance is the use of inheritance to simplify implementation of new facilities
6512 by making useful operations available for implementers of related new operations (sometimes called "programming by difference").
6514 A pure interface class is simply a set of pure virtual functions; see [I.25](#Ri-abstract).
6516 In early OOP (e.g., in the 1980s and 1990s), implementation inheritance and interface inheritance were often mixed
6517 and bad habits die hard.
6518 Even now, mixtures are not uncommon in old code bases and in old-style teaching material.
6520 The importance of keeping the two kinds of inheritance increases
6522 * with the size of a hierarchy (e.g., dozens of derived classes),
6523 * with the length of time the hierarchy is used (e.g., decades), and
6524 * with the number of distinct organizations in which a hierarchy is used
6525 (e.g., it can be difficult to distribute an update to a base class)
6528 ##### Example, bad
6530     class Shape {   // BAD, mixed interface and implementation
6531     public:
6532         Shape();
6533         Shape(Point ce = {0, 0}, Color co = none): cent{ce}, col {co} { /* ... */}
6535         Point center() const { return cent; }
6536         Color color() const { return col; }
6538         virtual void rotate(int) = 0;
6539         virtual void move(Point p) { cent = p; redraw(); }
6541         virtual void redraw();
6543         // ...
6544     public:
6545         Point cent;
6546         Color col;
6547     };
6549     class Circle : public Shape {
6550     public:
6551         Circle(Point c, int r) :Shape{c}, rad{r} { /* ... */ }
6553         // ...
6554     private:
6555         int rad;
6556     };
6558     class Triangle : public Shape {
6559     public:
6560         Triangle(Point p1, Point p2, Point p3); // calculate center
6561         // ...
6562     };
6564 Problems:
6566 * As the hierarchy grows and more data is added to `Shape`, the constructors gets harder to write and maintain.
6567 * Why calculate the center for the `Triangle`? we may never us it.
6568 * Add a data member to `Shape` (e.g., drawing style or canvas)
6569 and all derived classes and all users needs to be reviewed, possibly changes, and probably recompiled.
6571 The implementation of `Shape::move()` is an example of implementation inheritance:
6572 we have defined `move()` once and for all for all derived classes.
6573 The more code there is in such base class member function implementations and the more data is shared by placing it in the base,
6574 the more benefits we gain - and the less stable the hierarchy is.
6576 ##### Example
6578 This Shape hierarchy can be rewritten using interface inheritance:
6580     class Shape {  // pure interface
6581     public:
6582         virtual Point center() const = 0;
6583         virtual Color color() const = 0;
6585         virtual void rotate(int) = 0;
6586         virtual void move(Point p) = 0;
6588         virtual void redraw() = 0;
6590         // ...
6591     };
6593 Note that a pure interface rarely have constructors: there is nothing to construct.
6595     class Circle : public Shape {
6596     public:
6597         Circle(Point c, int r, Color c) :cent{c}, rad{r}, col{c} { /* ... */ }
6599         Point center() const override { return cent; }
6600         Color color() const override { return col; }
6602         // ...
6603     private:
6604         Point cent;
6605         int rad;
6606         Color col;
6607     };
6609 The interface is now less brittle, but there is more work in implementing the member functions.
6610 For example, `center` has to be implemented by every class derived from `Shape`.
6612 ##### Example, dual hierarchy
6614 How can we gain the benefit of the stable hierarchies from implementation hierarchies and the benefit of implementation reuse from implementation inheritance.
6615 One popular technique is dual hierarchies.
6616 There are many ways of implementing the idea of dual hierarchies; here, we use a multiple-inheritance variant.
6618 First we devise a hierarchy of interface classes:
6620     class Shape {   // pure interface
6621     public:
6622         virtual Point center() const = 0;
6623         virtual Color color() const = 0;
6625         virtual void rotate(int) = 0;
6626         virtual void move(Point p) = 0;
6628         virtual void redraw() = 0;
6630         // ...
6631     };
6633     class Circle : public Shape {   // pure interface
6634     public:
6635         int radius() = 0;
6636         // ...
6637     };
6639 To make this interface useful, we must provide its implementation classes (here, named equivalently, but in the `Impl` namespace):
6641     class Impl::Shape : public Shape { // implementation
6642     public:
6643         // constructors, destructor
6644         // ...
6645         virtual Point center() const { /* ... */ }
6646         virtual Color color() const { /* ... */ }
6648         virtual void rotate(int) { /* ... */ }
6649         virtual void move(Point p) { /* ... */ }
6651         virtual void redraw() { /* ... */ }
6653         // ...
6654     };
6656 Now `Shape` is a poor example of a class with an implementation,
6657 but bear with us because this is just a simple example of a technique aimed at more complex hierarchies.
6659     class Impl::Circle : public Circle, public Impl::Shape {   // implementation
6660     public:
6661         // constructors, destructor
6663         int radius() { /* ... */ }
6664         // ...
6665     };
6667 And we could extend the hierarchies by adding a Smiley class (:-)):
6669     class Smiley : public Circle { // pure interface
6670     public:
6671         // ...
6672     };
6674     class Impl::Smiley : Public Smiley, public Impl::Circle {   // implementation
6675     public:
6676         // constructors, destructor
6677         // ...
6678     }
6680 There are now two hierarchies:
6682 * interface: Smiley -> Circle -> Shape
6683 * implementation: Impl::Smiley -> Impl::Circle -> Impl::Shape
6685 Since each implementation derived from its interface as well as its implementation base class we get a lattice (DAG):
6687     Smiley     ->         Circle     ->  Shape
6688       ^                     ^               ^
6689       |                     |               |
6690     Impl::Smiley -> Impl::Circle -> Impl::Shape
6692 As mentioned, this is just one way to construct a dual hierarchy.
6694 Another (related) technique for separating interface and implementation is [PIMPL](#???).
6696 ##### Note
6698 There is often a choice between offering common functionality as (implemented) base class functions and free-standing functions
6699 (in an implementation namespace).
6700 Base classes gives a shorter notation and easier access to shared data (in the base)
6701 at the cost of the functionality being available only to users of the hierarchy.
6703 ##### Enforcement
6705 * Flag a derived to base conversion to a base with both data and virtual functions
6706 (except for calls from a derived class member to a base class member)
6707 * ???
6710 ### <a name="Rh-copy"></a>C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead
6712 ##### Reason
6714 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).
6716 ##### Example
6718     class Base {
6719     public:
6720         virtual owner<Base*> clone() = 0;
6721         virtual ~Base() = 0;
6723         Base(const Base&) = delete;
6724         Base& operator=(const Base&) = delete;
6725     };
6727     class Derived : public Base {
6728     public:
6729         owner<Derived*> clone() override;
6730         virtual ~Derived() override;
6731     };
6733 Note that because of language rules, the covariant return type cannot be a smart pointer. See also [C.67](#Rc-copy-virtual).
6735 ##### Enforcement
6737 * Flag a class with a virtual function and a non-user-defined copy operation.
6738 * Flag an assignment of base class objects (objects of a class from which another has been derived).
6740 ### <a name="Rh-get"></a>C.131: Avoid trivial getters and setters
6742 ##### Reason
6744 A trivial getter or setter adds no semantic value; the data item could just as well be `public`.
6746 ##### Example
6748     class Point {   // Bad: verbose
6749         int x;
6750         int y;
6751     public:
6752         Point(int xx, int yy) : x{xx}, y{yy} { }
6753         int get_x() const { return x; }
6754         void set_x(int xx) { x = xx; }
6755         int get_y() const { return y; }
6756         void set_y(int yy) { y = yy; }
6757         // no behavioral member functions
6758     };
6760 Consider making such a class a `struct` -- that is, a behaviorless bunch of variables, all public data and no member functions.
6762     struct Point {
6763         int x {0};
6764         int y {0};
6765     };
6767 Note that we can put default initializers on member variables: [C.49: Prefer initialization to assignment in constructors](#Rc-initialize).
6769 ##### Note
6771 The key to this rule is whether the semantics of the getter/setter are trivial. While it is not a complete definition of "trivial", consider whether there would be any difference beyond syntax if the getter/setter was a public data member instead. Examples of non-trivial semantics would be: maintaining a class invariant or converting between an internal type and an interface type.
6773 ##### Enforcement
6775 Flag multiple `get` and `set` member functions that simply access a member without additional semantics.
6777 ### <a name="Rh-virtual"></a>C.132: Don't make a function `virtual` without reason
6779 ##### Reason
6781 Redundant `virtual` increases run-time and object-code size.
6782 A virtual function can be overridden and is thus open to mistakes in a derived class.
6783 A virtual function ensures code replication in a templated hierarchy.
6785 ##### Example, bad
6787     template<class T>
6788     class Vector {
6789     public:
6790         // ...
6791         virtual int size() const { return sz; }   // bad: what good could a derived class do?
6792     private:
6793         T* elem;   // the elements
6794         int sz;    // number of elements
6795     };
6797 This kind of "vector" isn't meant to be used as a base class at all.
6799 ##### Enforcement
6801 * Flag a class with virtual functions but no derived classes.
6802 * Flag a class where all member functions are virtual and have implementations.
6804 ### <a name="Rh-protected"></a>C.133: Avoid `protected` data
6806 ##### Reason
6808 `protected` data is a source of complexity and errors.
6809 `protected` data complicated the statement of invariants.
6810 `protected` data inherently violates the guidance against putting data in base classes, which usually leads to having to deal virtual inheritance as well.
6812 ##### Example, bad
6814    class Shape {
6815    public:
6816         // ... interface functions ...
6817    protected:
6818         // data for use in derived classes:
6819         Color fill_color;
6820         Color edge_color;
6821         Style st;
6822    };
6824 Now it is up to every derived `Shape` to manipulate the protected data correctly.
6825 This has been popular, but also a major source of maintenance problems.
6826 In a large class hierarchy, the consistent use of protected data is hard to maintain because there can be a lot of code,
6827 spread over a lot of classes.
6828 The set of classes that can touch that data is open: anyone can derive a new class and start manipulating the protected data.
6829 Often, it is not possible to examine the complete set of classes so any change to the representation of the class becomes infeasible.
6830 There is no enforced invariant for the protected data; it is much like a set of global variables.
6831 The protected data has de facto become global to a large body of code.
6833 ##### Note
6835 Protected data often looks tempting to enable arbitrary improvements through derivation.
6836 Often, what you get is unprincipled changes and errors.
6837 [Prefer `private` data](#Rc-private) with a well-specified and enforced invariant.
6838 Alternative, and often better, [keep data out of any class used as an interface](#Rh-abstract).
6840 ##### Note
6842 Protected member function can be just fine.
6844 ##### Enforcement
6846 Flag classes with `protected` data.
6848 ### <a name="Rh-public"></a>C.134: Ensure all non-`const` data members have the same access level
6850 ##### Reason
6852 Prevention of logical confusion leading to errors.
6853 If the non-`const` data members don't have the same access level, the type is confused about what it's trying to do.
6854 Is it a type that maintains an invariant or simply a collection of values?
6856 ##### Discussion
6858 The core question is: What code is responsible for maintaining a meaningful/correct value for that variable?
6860 There are exactly two kinds of data members:
6862 * A: Ones that don't participate in the object's invariant. Any combination of values for these members is valid.
6863 * 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.
6865 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.
6867 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.
6869 Most classes are either all A or all B:
6871 * *All public*: If you're writing an aggregate bundle-of-variables without an invariant across those variables, then all the variables should be `public`.
6872   [By convention, declare such classes `struct` rather than `class`](#Rc-struct)
6873 * *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.
6875 ##### Exception
6877 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`).
6879 ##### Enforcement
6881 Flag any class that has non-`const` data members with different access levels.
6883 ### <a name="Rh-mi-interface"></a>C.135: Use multiple inheritance to represent multiple distinct interfaces
6885 ##### Reason
6887 Not all classes will necessarily support all interfaces, and not all callers will necessarily want to deal with all operations.
6888 Especially to break apart monolithic interfaces into "aspects" of behavior supported by a given derived class.
6890 ##### Example
6892     class iostream : public istream, public ostream {   // very simplified
6893         // ...
6894     };
6896 `istream` provides the interface to input operations; `ostream` provides the interface to output operations.
6897 `iostream` provides the union of the `istream` and `ostream` interfaces and the synchronization needed to allow both on a single stream. 
6899 ##### Note
6901 This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common
6902 and such interfaces are often not easily or naturally organized into a single-rooted hierarchy.
6904 ##### Note
6906 Such interfaces are typically abstract classes.
6908 ##### Enforcement
6912 ### <a name="Rh-mi-implementation"></a>C.136: Use multiple inheritance to represent the union of implementation attributes
6914 ##### Reason
6916 Some forms of mixins have state and often operations on that state.
6917 If the operations are virtual the use of inheritance is necessary, if not using inheritance can avoid boilerplate and forwarding.
6919 ##### Example
6921       class iostream : public istream, public ostream {   // very simplified
6922         // ...
6923     };
6925 `istream` provides the interface to input operations (and some data); `ostream` provides the interface to output operations (and some data).
6926 `iostream` provides the union of the `istream` and `ostream` interfaces and the synchronization needed to allow both on a single stream. 
6928 ##### Note
6930 This a relatively rare use because implementation can often be organized into a single-rooted hierarchy.
6932 ##### Example
6934 Sometimes, an "implementation attribute" is more like a "mixin" that determine the behavior of an implementation and inject
6935 members to enable the implementation of the policies it requires. 
6936 For example, see `std::enable_shared_from_this`
6937 or various bases from boost.intrusive (e.g. `list_base_hook` or `intrusive_ref_counter`).
6939 ##### Enforcement
6941 ??? 
6943 ### <a name="Rh-vbase"></a>C.137: Use `virtual` bases to avoid overly general base classes
6945 ##### Reason
6947  Allow separation of shared data and interface.
6948  To avoid all shared data to being put into an ultimate base class.
6950 ##### Example
6952     struct Interface {
6953         virtual void f();
6954         virtual int g();
6955         // ... no data here ...
6956     };
6958     class Utility {  // with data
6959         void utility1();
6960         virtual void utility2();    // customization point
6961     public:
6962         int x;
6963         int y;
6964     };
6966     class Derive1 : public Interface, virtual protected Utility {
6967         // override Interface functions
6968         // Maybe override Utility virtual functions
6969         // ...
6970     };
6972     class Derive2 : public Interface, virtual protected Utility {
6973         // override Interface functions
6974         // Maybe override Utility virtual functions
6975         // ...
6976     };
6978 Factoring out `Utility` makes sense if many derived classes share significant "implementation details."
6981 ##### Note
6983 Obviously, the example is too "theoretical", but it is hard to find a *small* realistic example.
6984 `Interface` is the root of an [interface hierarchy](#Rh-abstract)
6985 and `Utility` is the root of an [implementation hierarchy](Rh-kind).
6986 Here is [a slightly more realistic example](https://www.quora.com/What-are-the-uses-and-advantages-of-virtual-base-class-in-C%2B%2B/answer/Lance-Diduck?srid=tzNb) with an explanation.
6988 ##### Note
6990 Often, linearization of a hierarchy is a better solution.
6992 ##### Enforcement
6994 Flag mixed interface and implementation hierarchies.
6996 ### <a name="Rh-using"></a>C.138: Create an overload set for a derived class and its bases with `using`
6998 ##### Reason
7000 Without a using declaration, member functions in the derived class hide the entire inherited overload sets.
7002 ##### Example, bad
7004     #include <iostream>
7005     class B {
7006     public:
7007         virtual int f(int i) { std::cout << "f(int): "; return i; }
7008         virtual double f(double d) { std::cout << "f(double): "; return d; }
7009     };
7010     class D: public B {
7011     public:
7012         int f(int i) override { std::cout << "f(int): "; return i+1; }
7013     };
7014     int main()
7015     {
7016         D d;
7017         std::cout << d.f(2) << '\n';   // prints "f(int): 3"
7018         std::cout << d.f(2.3) << '\n'; // prints "f(int): 3"
7019     }
7021 ##### Example, good
7023     class D: public B {
7024     public:
7025         int f(int i) override { std::cout << "f(int): "; return i+1; }
7026         using B::f; // exposes f(double)
7027     };
7029 ##### Note
7031 This issue affects both virtual and non-virtual member functions
7033 For variadic bases, C++17 introduced a variadic form of the using-declaration,
7035     template <class... Ts>
7036     struct Overloader : Ts... {
7037         using Ts::operator()...; // exposes operator() from every base
7038     };
7040 ##### Enforcement
7042 Diagnose name hiding
7044 ### <a name="Rh-final"></a>C.139: Use `final` sparingly
7046 ##### Reason
7048 Capping a hierarchy with `final` is rarely needed for logical reasons and can be damaging to the extensibility of a hierarchy.
7049 Capping an individual virtual function with `final` is error-prone as that `final` can easily be overlooked when defining/overriding a set of functions.
7051 ##### Example, bad
7053     class Widget { /* ... */ };
7055     // nobody will ever want to improve My_widget (or so you thought)
7056     class My_widget final : public Widget { /* ... */ };
7058     class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that
7060 ##### Example, bad
7062     struct Interface {
7063         virtual int f() = 0;
7064         virtual int g() = 0;
7065     };
7067     class My_implementation : public Interface {
7068         int f() override;
7069         int g() final;  // I want g() to be FAST!
7070         // ...
7071     };
7073     class Better_implementation : public My_implementation {
7074         int f();
7075         int g();
7076         // ...
7077     };
7079     void use(Interface* p)
7080     {
7081         int x = p->f();    // Better_implementation::f()
7082         int y = p->g();    // My_implementation::g() Surprise?
7083     }
7085     // ...
7087     use(new Better_implementation{});
7089 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.
7090 Consistent use of `override` would catch this.
7092 ##### Note
7094 Not every class is meant to be a base class.
7095 Most standard-library classes are examples of that (e.g., `std::vector` and `std::string` are not designed to be derived from).
7096 This rule is about using `final` on classes with virtual functions meant to be interfaces for a class hierarchy.
7098 ##### Note
7100 Claims of performance improvements from `final` should be substantiated.
7101 Too often, such claims are based on conjecture or experience with other languages.
7103 There are examples where `final` can be important for both logical and performance reasons.
7104 One example is a performance-critical AST hierarchy in a compiler or language analysis tool.
7105 New derived classes are not added every year and only by library implementers.
7106 However, misuses are (or at least have been) far more common.
7108 ##### Enforcement
7110 Flag uses of `final`.
7113 ## <a name="Rh-virtual-default-arg"></a>C.140: Do not provide different default arguments for a virtual function and an overrider
7115 ##### Reason
7117 That can cause confusion: An overrider does not inherit default arguments.
7119 ##### Example, bad
7121     class Base {
7122     public:
7123         virtual int multiply(int value, int factor = 2) = 0;
7124     };
7126     class Derived : public Base {
7127     public:
7128         int multiply(int value, int factor = 10) override;
7129     };
7131     Derived d;
7132     Base& b = d;
7134     b.multiply(10);  // these two calls will call the same function but
7135     d.multiply(10);  // with different arguments and so different results
7137 ##### Enforcement
7139 Flag default arguments on virtual functions if they differ between base and derived declarations.
7141 ## C.hier-access: Accessing objects in a hierarchy
7143 ### <a name="Rh-poly"></a>C.145: Access polymorphic objects through pointers and references
7145 ##### Reason
7147 If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
7149 ##### Example
7151     struct B { int a; virtual int f(); };
7152     struct D : B { int b; int f() override; };
7154     void use(B b)
7155     {
7156         D d;
7157         B b2 = d;   // slice
7158         B b3 = b;
7159     }
7161     void use2()
7162     {
7163         D d;
7164         use(d);   // slice
7165     }
7167 Both `d`s are sliced.
7169 ##### Exception
7171 You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
7173     void use3()
7174     {
7175         D d;
7176         d.f();   // OK
7177     }
7179 ##### Enforcement
7181 Flag all slicing.
7183 ### <a name="Rh-dynamic_cast"></a>C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable
7185 ##### Reason
7187 `dynamic_cast` is checked at run time.
7189 ##### Example
7191     struct B {   // an interface
7192         virtual void f();
7193         virtual void g();
7194     };
7196     struct D : B {   // a wider interface
7197         void f() override;
7198         virtual void h();
7199     };
7201     void user(B* pb)
7202     {
7203         if (D* pd = dynamic_cast<D*>(pb)) {
7204             // ... use D's interface ...
7205         }
7206         else {
7207             // ... make do with B's interface ...
7208         }
7209     }
7211 ##### Note
7213 Like other casts, `dynamic_cast` is overused.
7214 [Prefer virtual functions to casting](#???).
7215 Prefer [static polymorphism](#???) to hierarchy navigation where it is possible (no run-time resolution necessary)
7216 and reasonably convenient.
7218 ##### Note
7220 Some people use `dynamic_cast` where a `typeid` would have been more appropriate;
7221 `dynamic_cast` is a general "is kind of" operation for discovering the best interface to an object,
7222 whereas `typeid` is a "give me the exact type of this object" operation to discover the actual type of an object.
7223 The latter is an inherently simpler operation that ought to be faster.
7224 The latter (`typeid`) is easily hand-crafted if necessary (e.g., if working on a system where RTTI is -- for some reason -- prohibited),
7225 the former (`dynamic_cast`) is far harder to implement correctly in general.
7227 Consider:
7229     struct B {
7230         const char * name {"B"};
7231         virtual const char* id() const { return name; }
7232         // ...
7233     };
7235     struct D : B {
7236         const char * name {"D"};
7237         const char* id() const override { return name; }
7238         // ...
7239     };
7241     void use()
7242     {
7243         B* pb1 = new B;
7244         B* pb2 = new D;
7246         cout << pb1->id(); // "B"
7247         cout << pb2->id(); // "D"
7249         if (pb1->id() == pb2->id()) // *pb1 is the same type as *pb2
7250         if (pb2->id() == "D") {         // looks innocent
7251             D* pd = static_cast<D*>(pb1);
7252             // ...
7253         }
7254         // ...
7255     }
7257 The result of `pb2->id() == "D"` is actually implementation defined.
7258 We added it to warn of the dangers of home-brew RTTI.
7259 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.
7261 If you implement your own RTTI, be careful.
7263 ##### Exception
7265 If your implementation provided a really slow `dynamic_cast`, you may have to use a workaround.
7266 However, all workarounds that cannot be statically resolved involve explicit casting (typically `static_cast`) and are error-prone.
7267 You will basically be crafting your own special-purpose `dynamic_cast`.
7268 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)
7269 and that your use of `dynamic_cast` is really performance critical.
7271 We are of the opinion that current implementations of `dynamic_cast` are unnecessarily slow.
7272 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).
7273 However, compatibility makes changes difficult even if all agree that an effort to optimize is worthwhile.
7275 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.
7277 ##### Enforcement
7279 Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`.
7281 ### <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
7283 ##### Reason
7285 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.
7287 ##### Example
7289     ???
7291 ##### Enforcement
7295 ### <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
7297 ##### Reason
7301 ##### Example
7303     ???
7305 ##### Enforcement
7309 ### <a name="Rh-smart"></a>C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`
7311 ##### Reason
7313 Avoid resource leaks.
7315 ##### Example
7317     void use(int i)
7318     {
7319         auto p = new int {7};           // bad: initialize local pointers with new
7320         auto q = make_unique<int>(9);   // ok: guarantee the release of the memory allocated for 9
7321         if (0 < i) return;              // maybe return and leak
7322         delete p;                       // too late
7323     }
7325 ##### Enforcement
7327 * Flag initialization of a naked pointer with the result of a `new`
7328 * Flag `delete` of local variable
7330 ### <a name="Rh-make_unique"></a>C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s
7332 ##### Reason
7334  `make_unique` gives a more concise statement of the construction.
7335 It also ensures exception safety in complex expressions.
7337 ##### Example
7339     unique_ptr<Foo> p {new<Foo>{7}};   // OK: but repetitive
7341     auto q = make_unique<Foo>(7);      // Better: no repetition of Foo
7343     // Not exception-safe: the compiler may interleave the computations of arguments as follows:
7344     //
7345     // 1. allocate memory for Foo,
7346     // 2. construct Foo,
7347     // 3. call bar,
7348     // 4. construct unique_ptr<Foo>.
7349     //
7350     // If bar throws, Foo will not be destroyed, and the memory allocated for it will leak.
7351     f(unique_ptr<Foo>(new Foo()), bar());
7353     // Exception-safe: calls to functions are never interleaved.
7354     f(make_unique<Foo>(), bar());
7356 ##### Enforcement
7358 * Flag the repetitive usage of template specialization list `<Foo>`
7359 * Flag variables declared to be `unique_ptr<Foo>`
7361 ### <a name="Rh-make_shared"></a>C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s
7363 ##### Reason
7365  `make_shared` gives a more concise statement of the construction.
7366 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.
7368 ##### Example
7370     // OK: but repetitive; and separate allocations for the Foo and shared_ptr's use count
7371     shared_ptr<Foo> p {new<Foo>{7}};
7373     auto q = make_shared<Foo>(7);   // Better: no repetition of Foo; one object
7375 ##### Enforcement
7377 * Flag the repetitive usage of template specialization list`<Foo>`
7378 * Flag variables declared to be `shared_ptr<Foo>`
7380 ### <a name="Rh-array"></a>C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
7382 ##### Reason
7384 Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
7386 ##### Example
7388     struct B { int x; };
7389     struct D : B { int y; };
7391     void use(B*);
7393     D a[] = {{1, 2}, {3, 4}, {5, 6}};
7394     B* p = a;     // bad: a decays to &a[0] which is converted to a B*
7395     p[1].x = 7;   // overwrite D[0].y
7397     use(a);       // bad: a decays to &a[0] which is converted to a B*
7399 ##### Enforcement
7401 * Flag all combinations of array decay and base to derived conversions.
7402 * 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`
7404 ## <a name="SS-overload"></a>C.over: Overloading and overloaded operators
7406 You can overload ordinary functions, template functions, and operators.
7407 You cannot overload function objects.
7409 Overload rule summary:
7411 * [C.160: Define operators primarily to mimic conventional usage](#Ro-conventional)
7412 * [C.161: Use nonmember functions for symmetric operators](#Ro-symmetric)
7413 * [C.162: Overload operations that are roughly equivalent](#Ro-equivalent)
7414 * [C.163: Overload only for operations that are roughly equivalent](#Ro-equivalent-2)
7415 * [C.164: Avoid conversion operators](#Ro-conversion)
7416 * [C.165: Use `using` for customization points](#Ro-custom)
7417 * [C.166: Overload unary `&` only as part of a system of smart pointers and references](#Ro-address-of)
7418 * [C.167: Use an operator for an operation with its conventional meaning](#Ro-overload)
7419 * [C.168: Define overloaded operators in the namespace of their operands](#Ro-namespace)
7420 * [C.170: If you feel like overloading a lambda, use a generic lambda](#Ro-lambda)
7422 ### <a name="Ro-conventional"></a>C.160: Define operators primarily to mimic conventional usage
7424 ##### Reason
7426 Minimize surprises.
7428 ##### Example
7430     class X {
7431     public:
7432         // ...
7433         X& operator=(const X&); // member function defining assignment
7434         friend bool operator==(const X&, const X&); // == needs access to representation
7435                                                     // after a = b we have a == b
7436         // ...
7437     };
7439 Here, the conventional semantics is maintained: [Copies compare equal](#SS-copy).
7441 ##### Example, bad
7443     X operator+(X a, X b) { return a.v - b.v; }   // bad: makes + subtract
7445 ##### Note
7447 Non-member operators should be either friends or defined in [the same namespace as their operands](#Ro-namespace).
7448 [Binary operators should treat their operands equivalently](#Ro-symmetric).
7450 ##### Enforcement
7452 Possibly impossible.
7454 ### <a name="Ro-symmetric"></a>C.161: Use nonmember functions for symmetric operators
7456 ##### Reason
7458 If you use member functions, you need two.
7459 Unless you use a non-member function for (say) `==`, `a == b` and `b == a` will be subtly different.
7461 ##### Example
7463     bool operator==(Point a, Point b) { return a.x == b.x && a.y == b.y; }
7465 ##### Enforcement
7467 Flag member operator functions.
7469 ### <a name="Ro-equivalent"></a>C.162: Overload operations that are roughly equivalent
7471 ##### Reason
7473 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.
7475 ##### Example
7477 Consider:
7479     void print(int a);
7480     void print(int a, int base);
7481     void print(const string&);
7483 These three functions all print their arguments (appropriately). Conversely:
7485     void print_int(int a);
7486     void print_based(int a, int base);
7487     void print_string(const string&);
7489 These three functions all print their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code.
7491 ##### Enforcement
7495 ### <a name="Ro-equivalent-2"></a>C.163: Overload only for operations that are roughly equivalent
7497 ##### Reason
7499 Having the same name for logically different functions is confusing and leads to errors when using generic programming.
7501 ##### Example
7503 Consider:
7505     void open_gate(Gate& g);   // remove obstacle from garage exit lane
7506     void fopen(const char* name, const char* mode);   // open file
7508 The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:
7510     void open(Gate& g);   // remove obstacle from garage exit lane
7511     void open(const char* name, const char* mode ="r");   // open file
7513 The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion.
7514 Fortunately, the type system will catch many such mistakes.
7516 ##### Note
7518 Be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`.
7520 ##### Enforcement
7524 ### <a name="Ro-conversion"></a>C.164: Avoid conversion operators
7526 ##### Reason
7528 Implicit conversions can be essential (e.g., `double` to `int`) but often cause surprises (e.g., `String` to C-style string).
7530 ##### Note
7532 Prefer explicitly named conversions until a serious need is demonstrated.
7533 By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion)
7534 and frequently needed. Do not introduce implicit conversions (through conversion operators or non-`explicit` constructors)
7535 just to gain a minor convenience.
7537 ##### Example, bad
7539     class String {   // handle ownership and access to a sequence of characters
7540         // ...
7541         String(czstring p); // copy from *p to *(this->elem)
7542         // ...
7543         operator zstring() { return elem; }
7544         // ...
7545     };
7547     void user(zstring p)
7548     {
7549         if (*p == "") {
7550             String s {"Trouble ahead!"};
7551             // ...
7552             p = s;
7553         }
7554         // use p
7555     }
7557 The string allocated for `s` and assigned to `p` is destroyed before it can be used.
7559 ##### Enforcement
7561 Flag all conversion operators.
7563 ### <a name="Ro-custom"></a>C.165: Use `using` for customization points
7565 ##### Reason
7567 To find function objects and functions defined in a separate namespace to "customize" a common function.
7569 ##### Example
7571 Consider `swap`. It is a general (standard library) function with a definition that will work for just about any type.
7572 However, it is desirable to define specific `swap()`s for specific types.
7573 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.
7575     namespace N {
7576         My_type X { /* ... */ };
7577         void swap(X&, X&);   // optimized swap for N::X
7578         // ...
7579     }
7581     void f1(N::X& a, N::X& b)
7582     {
7583         std::swap(a, b);   // probably not what we wanted: calls std::swap()
7584     }
7586 The `std::swap()` in `f1()` does exactly what we asked it to do: it calls the `swap()` in namespace `std`.
7587 Unfortunately, that's probably not what we wanted.
7588 How do we get `N::X` considered?
7590     void f2(N::X& a, N::X& b)
7591     {
7592         swap(a, b);   // calls N::swap
7593     }
7595 But that may not be what we wanted for generic code.
7596 There, we typically want the specific function if it exists and the general function if not.
7597 This is done by including the general function in the lookup for the function:
7599     void f3(N::X& a, N::X& b)
7600     {
7601         using std::swap;  // make std::swap available
7602         swap(a, b);        // calls N::swap if it exists, otherwise std::swap
7603     }
7605 ##### Enforcement
7607 Unlikely, except for known customization points, such as `swap`.
7608 The problem is that the unqualified and qualified lookups both have uses.
7610 ### <a name="Ro-address-of"></a>C.166: Overload unary `&` only as part of a system of smart pointers and references
7612 ##### Reason
7614 The `&` operator is fundamental in C++.
7615 Many parts of the C++ semantics assumes its default meaning.
7617 ##### Example
7619     class Ptr { // a somewhat smart pointer
7620         Ptr(X* pp) :p(pp) { /* check */ }
7621         X* operator->() { /* check */ return p; }
7622         X operator[](int i);
7623         X operator*();
7624     private:
7625         T* p;
7626     };
7628     class X {
7629         Ptr operator&() { return Ptr{this}; }
7630         // ...
7631     };
7633 ##### Note
7635 If you "mess with" operator `&` be sure that its definition has matching meanings for `->`, `[]`, `*`, and `.` on the result type.
7636 Note that operator `.` currently cannot be overloaded so a perfect system is impossible.
7637 We hope to remedy that: <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf>.
7638 Note that `std::addressof()` always yields a built-in pointer.
7640 ##### Enforcement
7642 Tricky. Warn if `&` is user-defined without also defining `->` for the result type.
7644 ### <a name="Ro-namespace"></a>C.168: Define overloaded operators in the namespace of their operands
7646 ##### Reason
7648 Readability.
7649 Ability for find operators using ADL.
7650 Avoiding inconsistent definition in different namespaces
7652 ##### Example
7654     struct S { };
7655     bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
7656     S s;
7658     bool x = (s == s);
7660 This is what a default `==` would do, if we had such defaults.
7662 ##### Example
7664     namespace N {
7665         struct S { };
7666         bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
7667     }
7669     N::S s;
7671     bool x = (s == s);  // finds N::operator==() by ADL
7673 ##### Example, bad
7675     struct S { };
7676     S s;
7678     namespace N {
7679         S::operator!(S a) { return true; }
7680         S not_s = !s;
7681     }
7683     namespace M {
7684         S::operator!(S a) { return false; }
7685         S not_s = !s;
7686     }
7688 Here, the meaning of `!s` differs in `N` and `M`.
7689 This can be most confusing.
7690 Remove the definition of `namespace M` and the confusion is replaced by an opportunity to make the mistake.
7692 ##### Note
7694 If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule.
7695 For example:
7697     Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);
7699 This may be something best avoided.
7701 ##### See also
7703 This is a special case of the rule that [helper functions should be defined in the same namespace as their class](#Rc-helper).
7705 ##### Enforcement
7707 * Flag operator definitions that are not it the namespace of their operands
7709 ### <a name="Ro-overload"></a>C.167: Use an operator for an operation with its conventional meaning
7711 ##### Reason
7713 Readability. Convention. Reusability. Support for generic code
7715 ##### Example
7717     void cout_my_class(const My_class& c) // confusing, not conventional,not generic
7718     {
7719         std::cout << /* class members here */;
7720     }
7722     std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
7723     {
7724         return os << /* class members here */;
7725     }
7727 By itself, `cout_my_class` would be OK, but it is not usable/composable with code that rely on the `<<` convention for output:
7729     My_class var { /* ... */ };
7730     // ...
7731     cout << "var = " << var << '\n';
7733 ##### Note
7735 There are strong and vigorous conventions for the meaning most operators, such as
7737 * comparisons (`==`, `!=`, `<`, `<=`, `>`, and `>=`),
7738 * arithmetic operations (`+`, `-`, `*`, `/`, and `%`)
7739 * access operations (`.`, `->`, unary `*`, and `[]`)
7740 * assignment (`=`)
7742 Don't define those unconventionally and don't invent your own names for them.
7744 ##### Enforcement
7746 Tricky. Requires semantic insight.
7748 ### <a name="Ro-lambda"></a>C.170: If you feel like overloading a lambda, use a generic lambda
7750 ##### Reason
7752 You cannot overload by defining two different lambdas with the same name.
7754 ##### Example
7756     void f(int);
7757     void f(double);
7758     auto f = [](char);   // error: cannot overload variable and function
7760     auto g = [](int) { /* ... */ };
7761     auto g = [](double) { /* ... */ };   // error: cannot overload variables
7763     auto h = [](auto) { /* ... */ };   // OK
7765 ##### Enforcement
7767 The compiler catches the attempt to overload a lambda.
7769 ## <a name="SS-union"></a>C.union: Unions
7771 A `union` is a `struct` where all members start at the same address so that it can hold only one member at a time.
7772 A `union` does not keep track of which member is stored so the programmer has to get it right;
7773 this is inherently error-prone, but there are ways to compensate.
7775 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*.
7777 Union rule summary:
7779 * [C.180: Use `union`s to save Memory](#Ru-union)
7780 * [C.181: Avoid "naked" `union`s](#Ru-naked)
7781 * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous)
7782 * [C.183: Don't use a `union` for type punning](#Ru-pun)
7783 * ???
7785 ### <a name="Ru-union"></a>C.180: Use `union`s to save memory
7787 ##### Reason
7789 A `union` allows a single piece of memory to be used for different types of objects at different times.
7790 Consequently, it can be used to save memory when we have several objects that are never used at the same time.
7792 ##### Example
7794     union Value {
7795         int x;
7796         double d;
7797     };
7799     Value v = { 123 };  // now v holds an int
7800     cout << v.x << '\n';    // write 123
7801     v.d = 987.654;  // now v holds a double
7802     cout << v.d << '\n';    // write 987.654
7804 But heed the warning: [Avoid "naked" `union`s](#Ru-naked)
7806 ##### Example
7808     // Short-string optimization
7810     constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer
7812     class Immutable_string {
7813     public:
7814         Immutable_string(const char* str) :
7815             size(strlen(str))
7816         {
7817             if (size < buffer_size)
7818                 strcpy_s(string_buffer, buffer_size, str);
7819             else {
7820                 string_ptr = new char[size + 1];
7821                 strcpy_s(string_ptr, size + 1, str);
7822             }
7823         }
7825         ~Immutable_string()
7826         {
7827             if (size >= buffer_size)
7828                 delete string_ptr;
7829         }
7831         const char* get_str() const
7832         {
7833             return (size < buffer_size) ? string_buffer : string_ptr;
7834         }
7836     private:
7837         // If the string is short enough, we store the string itself
7838         // instead of a pointer to the string.
7839         union {
7840             char* string_ptr;
7841             char string_buffer[buffer_size];
7842         };
7844         const size_t size;
7845     };
7847 ##### Enforcement
7851 ### <a name="Ru-naked"></a>C.181: Avoid "naked" `union`s
7853 ##### Reason
7855 A *naked union* is a union without an associated indicator which member (if any) it holds,
7856 so that the programmer has to keep track.
7857 Naked unions are a source of type errors.
7859 ###### Example, bad
7861     union Value {
7862         int x;
7863         double d;
7864     };
7866     Value v;
7867     v.d = 987.654;  // v holds a double
7869 So far, so good, but we can easily misuse the `union`:
7871     cout << v.x << '\n';    // BAD, undefined behavior: v holds a double, but we read it as an int
7873 Note that the type error happened without any explicit cast.
7874 When we tested that program the last value printed was `1683627180` which it the integer value for the bit pattern for `987.654`.
7875 What we have here is an "invisible" type error that happens to give a result that could easily look innocent.
7877 And, talking about "invisible", this code produced no output:
7879     v.x = 123;
7880     cout << v.d << '\n';    // BAD: undefined behavior
7882 ###### Alternative
7884 Wrap a `union` in a class together with a type field.
7886 The soon-to-be-standard `variant` type (to be found in `<variant>`) does that for you:
7888     variant<int, double> v;
7889     v = 123;        // v holds an int
7890     int x = get<int>(v);
7891     v = 123.456;    // v holds a double
7892     w = get<double>(v);
7894 ##### Enforcement
7898 ### <a name="Ru-anonymous"></a>C.182: Use anonymous `union`s to implement tagged unions
7900 ##### Reason
7902 A well-designed tagged union is type safe.
7903 An *anonymous* union simplifies the definition of a class with a (tag, union) pair.
7905 ##### Example
7907 This example is mostly borrowed from TC++PL4 pp216-218.
7908 You can look there for an explanation.
7910 The code is somewhat elaborate.
7911 Handling a type with user-defined assignment and destructor is tricky.
7912 Saving programmers from having to write such code is one reason for including `variant` in the standard.
7914     class Value { // two alternative representations represented as a union
7915     private:
7916         enum class Tag { number, text };
7917         Tag type; // discriminant
7919         union { // representation (note: anonymous union)
7920             int i;
7921             string s; // string has default constructor, copy operations, and destructor
7922         };
7923     public:
7924         struct Bad_entry { }; // used for exceptions
7926         ~Value();
7927         Value& operator=(const Value&);   // necessary because of the string variant
7928         Value(const Value&);
7929         // ...
7930         int number() const;
7931         string text() const;
7933         void set_number(int n);
7934         void set_text(const string&);
7935         // ...
7936     };
7938     int Value::number() const
7939     {
7940         if (type != Tag::number) throw Bad_entry{};
7941         return i;
7942     }
7944     string Value::text() const
7945     {
7946         if (type != Tag::text) throw Bad_entry{};
7947         return s;
7948     }
7950     void Value::set_number(int n)
7951     {
7952         if (type == Tag::text) {
7953             s.~string();      // explicitly destroy string
7954             type = Tag::number;
7955         }
7956         i = n;
7957     }
7959     void Value::set_text(const string& ss)
7960     {
7961         if (type == Tag::text)
7962             s = ss;
7963         else {
7964             new(&s) string{ss};   // placement new: explicitly construct string
7965             type = Tag::text;
7966         }
7967     }
7969     Value& Value::operator=(const Value& e)   // necessary because of the string variant
7970     {
7971         if (type == Tag::text && e.type == Tag::text) {
7972             s = e.s;    // usual string assignment
7973             return *this;
7974         }
7976         if (type == Tag::text) s.~string(); // explicit destroy
7978         switch (e.type) {
7979         case Tag::number:
7980             i = e.i;
7981             break;
7982         case Tag::text:
7983             new(&s)(e.s);   // placement new: explicit construct
7984             type = e.type;
7985         }
7987         return *this;
7988     }
7990     Value::~Value()
7991     {
7992         if (type == Tag::text) s.~string(); // explicit destroy
7993     }
7995 ##### Enforcement
7999 ### <a name="Ru-pun"></a>C.183: Don't use a `union` for type punning
8001 ##### Reason
8003 It is undefined behavior to read a `union` member with a different type from the one with which it was written.
8004 Such punning is invisible, or at least harder to spot than using a named cast.
8005 Type punning using a `union` is a source of errors.
8007 ##### Example, bad
8009     union Pun {
8010         int x;
8011         unsigned char c[sizeof(int)];
8012     };
8014 The idea of `Pun` is to be able to look at the character representation of an `int`.
8016     void bad(Pun& u)
8017     {
8018         u.x = 'x';
8019         cout << u.c[0] << '\n';     // undefined behavior
8020     }
8022 If you wanted to see the bytes of an `int`, use a (named) cast:
8024     void if_you_must_pun(int& x)
8025     {
8026         auto p = reinterpret_cast<unsigned char*>(&x);
8027         cout << p[0] << '\n';     // OK; better
8028         // ...
8029     }
8031 Accessing the result of an `reinterpret_cast` to a different type from the objects declared type is defined behavior (even though `reinterpret_cast` is discouraged),
8032 but at least we can see that something tricky is going on.
8034 ##### Note
8036 Unfortunately, `union`s are commonly used for type punning.
8037 We don't consider "sometimes, it works as expected" a strong argument.
8039 C++17 introduced a distinct type `std::byte` to facilitate operations on raw object representation.  Use that type instead of `unsigned char` or `char` for these operations.
8041 ##### Enforcement
8047 # <a name="S-enum"></a>Enum: Enumerations
8049 Enumerations are used to define sets of integer values and for defining types for such sets of values.
8050 There are two kind of enumerations, "plain" `enum`s and `class enum`s.
8052 Enumeration rule summary:
8054 * [Enum.1: Prefer enumerations over macros](#Renum-macro)
8055 * [Enum.2: Use enumerations to represent sets of related named constants](#Renum-set)
8056 * [Enum.3: Prefer `enum class`es over "plain" `enum`s](#Renum-class)
8057 * [Enum.4: Define operations on enumerations for safe and simple use](#Renum-oper)
8058 * [Enum.5: Don't use `ALL_CAPS` for enumerators](#Renum-caps)
8059 * [Enum.6: Avoid unnamed enumerations](#Renum-unnamed)
8060 * [Enum.7: Specify the underlying type of an enumeration only when necessary](#Renum-underlying)
8061 * [Enum.8: Specify enumerator values only when necessary](#Renum-value)
8063 ### <a name="Renum-macro"></a>Enum.1: Prefer enumerations over macros
8065 ##### Reason
8067 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.
8069 ##### Example
8071 First some bad old code:
8073     // webcolors.h (third party header)
8074     #define RED   0xFF0000
8075     #define GREEN 0x00FF00
8076     #define BLUE  0x0000FF
8078     // productinfo.h
8079     // The following define product subtypes based on color
8080     #define RED    0
8081     #define PURPLE 1
8082     #define BLUE   2
8084     int webby = BLUE;   // webby == 2; probably not what was desired
8086 Instead use an `enum`:
8088     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8089     enum class Product_info { red = 0, purple = 1, blue = 2 };
8091     int webby = blue;   // error: be specific
8092     Web_color webby = Web_color::blue;
8094 We used an `enum class` to avoid name clashes.
8096 ##### Enforcement
8098 Flag macros that define integer values.
8101 ### <a name="Renum-set"></a>Enum.2: Use enumerations to represent sets of related named constants
8103 ##### Reason
8105 An enumeration shows the enumerators to be related and can be a named type.
8109 ##### Example
8111     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8114 ##### Note
8116 Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:
8118     enum class Product_info { red = 0, purple = 1, blue = 2 };
8120     void print(Product_info inf)
8121     {
8122         switch (inf) {
8123         case Product_info::red: cout << "red"; break;
8124         case Product_info::purple: cout << "purple"; break;
8125         }
8126     }
8128 Such off-by-one switch`statements are often the results of an added enumerator and insufficient testing.
8130 ##### Enforcement
8132 * Flag `switch`-statements where the `case`s cover most but not all enumerators of an enumeration.
8133 * Flag `switch`-statements where the `case`s cover a few enumerators of an enumeration, but has no `default`.
8136 ### <a name="Renum-class"></a>Enum.3: Prefer class enums over "plain" enums
8138 ##### Reason
8140 To minimize surprises: traditional enums convert to int too readily.
8142 ##### Example
8144     void Print_color(int color);
8146     enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8147     enum Product_info { Red = 0, Purple = 1, Blue = 2 };
8149     Web_color webby = Web_color::blue;
8151     // Clearly at least one of these calls is buggy.
8152     Print_color(webby);
8153     Print_color(Product_info::Blue);
8155 Instead use an `enum class`:
8157     void Print_color(int color);
8159     enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
8160     enum class Product_info { red = 0, purple = 1, blue = 2 };
8162     Web_color webby = Web_color::blue;
8163     Print_color(webby);  // Error: cannot convert Web_color to int.
8164     Print_color(Product_info::Red);  // Error: cannot convert Product_info to int.
8166 ##### Enforcement
8168 (Simple) Warn on any non-class `enum` definition.
8170 ### <a name="Renum-oper"></a>Enum.4: Define operations on enumerations for safe and simple use
8172 ##### Reason
8174 Convenience of use and avoidance of errors.
8176 ##### Example
8178     enum class Day { mon, tue, wed, thu, fri, sat, sun };
8180     Day operator++(Day& d)
8181     {
8182         return d == Day::sun ? Day::mon : Day{++d};
8183     }
8185     Day today = Day::sat;
8186     Day tomorrow = ++today;
8188 ##### Enforcement
8190 Flag repeated expressions cast back into an enumeration.
8193 ### <a name="Renum-caps"></a>Enum.5: Don't use `ALL_CAPS` for enumerators
8195 ##### Reason
8197 Avoid clashes with macros.
8199 ##### Example, bad
8201      // webcolors.h (third party header)
8202     #define RED   0xFF0000
8203     #define GREEN 0x00FF00
8204     #define BLUE  0x0000FF
8206     // productinfo.h
8207     // The following define product subtypes based on color
8209     enum class Product_info { RED, PURPLE, BLUE };   // syntax error
8211 ##### Enforcement
8213 Flag ALL_CAPS enumerators.
8215 ### <a name="Renum-unnamed"></a>Enum.6: Avoid unnamed enumerations
8217 ##### Reason
8219 If you can't name an enumeration, the values are not related
8221 ##### Example, bad
8223     enum { red = 0xFF0000, scale = 4, is_signed = 1 };
8225 Such code is not uncommon in code written before there were convenient alternative ways of specifying integer constants.
8227 ##### Alternative
8229 Use `constexpr` values instead. For example:
8231     constexpr int red = 0xFF0000;
8232     constexpr short scale = 4;
8233     constexpr bool is_signed = true;
8235 ##### Enforcement
8237 Flag unnamed enumerations.
8240 ### <a name="Renum-underlying"></a>Enum.7: Specify the underlying type of an enumeration only when necessary
8242 ##### Reason
8244 The default is the easiest to read and write.
8245 `int` is the default integer type.
8246 `int` is compatible with C `enum`s.
8248 ##### Example
8250     enum class Direction : char { n, s, e, w,
8251                                   ne, nw, se, sw };  // underlying type saves space
8253     enum class Web_color : int { red   = 0xFF0000,
8254                                  green = 0x00FF00,
8255                                  blue  = 0x0000FF };  // underlying type is redundant
8257 ##### Note
8259 Specifying the underlying type is necessary in forward declarations of enumerations:
8261     enum Flags : char;
8263     void f(Flags);
8265     // ....
8267     enum flags : char { /* ... */ };
8270 ##### Enforcement
8272 ????
8275 ### <a name="Renum-value"></a>Enum.8: Specify enumerator values only when necessary
8277 ##### Reason
8279 It's the simplest.
8280 It avoids duplicate enumerator values.
8281 The default gives a consecutive set of values that is good for `switch`-statement implementations.
8283 ##### Example
8285     enum class Col1 { red, yellow, blue };
8286     enum class Col2 { red = 1, yellow = 2, blue = 2 }; // typo
8287     enum class Month { jan = 1, feb, mar, apr, may, jun,
8288                        jul, august, sep, oct, nov, dec }; // starting with 1 is conventional
8289     enum class Base_flag { dec = 1, oct = dec << 1, hex = dec << 2 }; // set of bits
8291 Specifying values is necessary to match conventional values (e.g., `Month`)
8292 and where consecutive values are undesirable (e.g., to get separate bits as in `Base_flag`).
8294 ##### Enforcement
8296 * Flag duplicate enumerator values
8297 * Flag explicitly specified all-consecutive enumerator values
8300 # <a name="S-resource"></a>R: Resource management
8302 This section contains rules related to resources.
8303 A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks.
8304 The reason it must be released is typically that it can be in short supply, so even delayed release may do harm.
8305 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.
8306 An entity that is responsible for releasing a resource is called an owner.
8308 There are a few cases where leaks can be acceptable or even optimal:
8309 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.
8310 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.
8311 Here, we ignore such cases.
8313 * Resource management rule summary:
8315   * [R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)](#Rr-raii)
8316   * [R.2: In interfaces, use raw pointers to denote individual objects (only)](#Rr-use-ptr)
8317   * [R.3: A raw pointer (a `T*`) is non-owning](#Rr-ptr)
8318   * [R.4: A raw reference (a `T&`) is non-owning](#Rr-ref)
8319   * [R.5: Prefer scoped objects, don't heap-allocate unnecessarily](#Rr-scoped)
8320   * [R.6: Avoid non-`const` global variables](#Rr-global)
8322 * Allocation and deallocation rule summary:
8324   * [R.10: Avoid `malloc()` and `free()`](#Rr-mallocfree)
8325   * [R.11: Avoid calling `new` and `delete` explicitly](#Rr-newdelete)
8326   * [R.12: Immediately give the result of an explicit resource allocation to a manager object](#Rr-immediate-alloc)
8327   * [R.13: Perform at most one explicit resource allocation in a single expression statement](#Rr-single-alloc)
8328   * [R.14: ??? array vs. pointer parameter](#Rr-ap)
8329   * [R.15: Always overload matched allocation/deallocation pairs](#Rr-pair)
8331 * <a name="Rr-summary-smartptrs"></a>Smart pointer rule summary:
8333   * [R.20: Use `unique_ptr` or `shared_ptr` to represent ownership](#Rr-owner)
8334   * [R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership](#Rr-unique)
8335   * [R.22: Use `make_shared()` to make `shared_ptr`s](#Rr-make_shared)
8336   * [R.23: Use `make_unique()` to make `unique_ptr`s](#Rr-make_unique)
8337   * [R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s](#Rr-weak_ptr)
8338   * [R.30: Take smart pointers as parameters only to explicitly express lifetime semantics](#Rr-smartptrparam)
8339   * [R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`](#Rr-smart)
8340   * [R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`](#Rr-uniqueptrparam)
8341   * [R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the `widget`](#Rr-reseat)
8342   * [R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner](#Rr-sharedptrparam-owner)
8343   * [R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer](#Rr-sharedptrparam)
8344   * [R.36: Take a `const shared_ptr<widget>&` parameter to express that it might retain a reference count to the object ???](#Rr-sharedptrparam-const)
8345   * [R.37: Do not pass a pointer or reference obtained from an aliased smart pointer](#Rr-smartptrget)
8347 ### <a name="Rr-raii"></a>R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)
8349 ##### Reason
8351 To avoid leaks and the complexity of manual resource management.
8352 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`.
8353 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.
8355 ##### Example, bad
8357 Consider:
8359     void send(X* x, cstring_span destination)
8360     {
8361         auto port = open_port(destination);
8362         my_mutex.lock();
8363         // ...
8364         send(port, x);
8365         // ...
8366         my_mutex.unlock();
8367         close_port(port);
8368         delete x;
8369     }
8371 In this code, you have to remember to `unlock`, `close_port`, and `delete` on all paths, and do each exactly once.
8372 Further, if any of the code marked `...` throws an exception, then `x` is leaked and `my_mutex` remains locked.
8374 ##### Example
8376 Consider:
8378     void send(unique_ptr<X> x, cstring_span destination)  // x owns the X
8379     {
8380         Port port{destination};            // port owns the PortHandle
8381         lock_guard<mutex> guard{my_mutex}; // guard owns the lock
8382         // ...
8383         send(port, x);
8384         // ...
8385     } // automatically unlocks my_mutex and deletes the pointer in x
8387 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.
8389 What is `Port`? A handy wrapper that encapsulates the resource:
8391     class Port {
8392         PortHandle port;
8393     public:
8394         Port(cstring_span destination) : port{open_port(destination)} { }
8395         ~Port() { close_port(port); }
8396         operator PortHandle() { return port; }
8398         // port handles can't usually be cloned, so disable copying and assignment if necessary
8399         Port(const Port&) = delete;
8400         Port& operator=(const Port&) = delete;
8401     };
8403 ##### Note
8405 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)
8407 **See also**: [RAII](#Rr-raii).
8409 ### <a name="Rr-use-ptr"></a>R.2: In interfaces, use raw pointers to denote individual objects (only)
8411 ##### Reason
8413 Arrays are best represented by a container type (e.g., `vector` (owning)) or a `span` (non-owning).
8414 Such containers and views hold sufficient information to do range checking.
8416 ##### Example, bad
8418     void f(int* p, int n)   // n is the number of elements in p[]
8419     {
8420         // ...
8421         p[2] = 7;   // bad: subscript raw pointer
8422         // ...
8423     }
8425 The compiler does not read comments, and without reading other code you do not know whether `p` really points to `n` elements.
8426 Use a `span` instead.
8428 ##### Example
8430     void g(int* p, int fmt)   // print *p using format #fmt
8431     {
8432         // ... uses *p and p[0] only ...
8433     }
8435 ##### Exception
8437 C-style strings are passed as single pointers to a zero-terminated sequence of characters.
8438 Use `zstring` rather than `char*` to indicate that you rely on that convention.
8440 ##### Note
8442 Many current uses of pointers to a single element could be references.
8443 However, where `nullptr` is a possible value, a reference may not be an reasonable alternative.
8445 ##### Enforcement
8447 * Flag pointer arithmetic (including `++`) on a pointer that is not part of a container, view, or iterator.
8448   This rule would generate a huge number of false positives if applied to an older code base.
8449 * Flag array names passed as simple pointers
8451 ### <a name="Rr-ptr"></a>R.3: A raw pointer (a `T*`) is non-owning
8453 ##### Reason
8455 There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning.
8456 We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
8458 ##### Example
8460     void f()
8461     {
8462         int* p1 = new int{7};           // bad: raw owning pointer
8463         auto p2 = make_unique<int>(7);  // OK: the int is owned by a unique pointer
8464         // ...
8465     }
8467 The `unique_ptr` protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The `T*` does not.
8469 ##### Example
8471     template<typename T>
8472     class X {
8473         // ...
8474     public:
8475         T* p;   // bad: it is unclear whether p is owning or not
8476         T* q;   // bad: it is unclear whether q is owning or not
8477     };
8479 We can fix that problem by making ownership explicit:
8481     template<typename T>
8482     class X2 {
8483         // ...
8484     public:
8485         owner<T*> p;  // OK: p is owning
8486         T* q;         // OK: q is not owning
8487     };
8489 ##### Exception
8491 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.
8492 The fact that there are billions of lines of code that violate this rule against owning `T*`s cannot be ignored.
8493 We'd love to see program transformation tools turning 20-year-old "legacy" code into shiny modern code,
8494 we encourage the development, deployment and use of such tools,
8495 we hope the guidelines will help the development of such tools,
8496 and we even contributed (and contribute) to the research and development in this area.
8497 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.
8499 This code cannot all be rewritten (ever assuming good code transformation software), especially not soon.
8500 This problem cannot be solved (at scale) by transforming all owning pointers to `unique_ptr`s and `shared_ptr`s,
8501 partly because we need/use owning "raw pointers" as well as simple pointers in the implementation of our fundamental resource handles.
8502 For example, common `vector` implementations have one owning pointer and two non-owning pointers.
8503 Many ABIs (and essentially all interfaces to C code) use `T*`s, some of them owning.
8504 Some interfaces cannot be simply annotated with `owner` because they need to remain compilable as C
8505 (although this would be a rare good use for a macro, that expands to `owner` in C++ mode only).
8507 ##### Note
8509 `owner<T*>` has no default semantics beyond `T*`. It can be used without changing any code using it and without affecting ABIs.
8510 It is simply a indicator to programmers and analysis tools.
8511 For example, if an `owner<T*>` is a member of a class, that class better have a destructor that `delete`s it.
8513 ##### Example, bad
8515 Returning a (raw) pointer imposes a life-time management uncertainty on the caller; that is, who deletes the pointed-to object?
8517     Gadget* make_gadget(int n)
8518     {
8519         auto p = new Gadget{n};
8520         // ...
8521         return p;
8522     }
8524     void caller(int n)
8525     {
8526         auto p = make_gadget(n);   // remember to delete p
8527         // ...
8528         delete p;
8529     }
8531 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)):
8533     Gadget make_gadget(int n)
8534     {
8535         Gadget g{n};
8536         // ...
8537         return g;
8538     }
8540 ##### Note
8542 This rule applies to factory functions.
8544 ##### Note
8546 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."
8548 ##### Enforcement
8550 * (Simple) Warn on `delete` of a raw pointer that is not an `owner<T>`.
8551 * (Moderate) Warn on failure to either `reset` or explicitly `delete` an `owner<T>` pointer on every code path.
8552 * (Simple) Warn if the return value of `new` is assigned to a raw pointer.
8553 * (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor.
8554   Suggest considering returning it by value instead.
8556 ### <a name="Rr-ref"></a>R.4: A raw reference (a `T&`) is non-owning
8558 ##### Reason
8560 There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning.
8561 We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
8563 ##### Example
8565     void f()
8566     {
8567         int& r = *new int{7};  // bad: raw owning reference
8568         // ...
8569         delete &r;             // bad: violated the rule against deleting raw pointers
8570     }
8572 **See also**: [The raw pointer rule](#Rr-ptr)
8574 ##### Enforcement
8576 See [the raw pointer rule](#Rr-ptr)
8578 ### <a name="Rr-scoped"></a>R.5: Prefer scoped objects, don't heap-allocate unnecessarily
8580 ##### Reason
8582 A scoped object is a local object, a global object, or a member.
8583 This implies that there is no separate allocation and deallocation cost in excess of that already used for the containing scope or object.
8584 The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.
8586 ##### Example
8588 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:
8590     void f(int n)
8591     {
8592         auto p = new Gadget{n};
8593         // ...
8594         delete p;
8595     }
8597 Instead, use a local variable:
8599     void f(int n)
8600     {
8601         Gadget g{n};
8602         // ...
8603     }
8605 ##### Enforcement
8607 * (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.
8608 * (Simple) Warn if a local `Unique_ptr` or `Shared_ptr` is not moved, copied, reassigned or `reset` before its lifetime ends.
8610 ### <a name="Rr-global"></a>R.6: Avoid non-`const` global variables
8612 ##### Reason
8614 Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects.
8615 They are a notable source of errors.
8617 **Warning**: The initialization of global objects is not totally ordered.
8618 If you use a global object initialize it with a constant.
8619 Note that it is possible to get undefined initialization order even for `const` objects.
8621 ##### Exception
8623 A global object is often better than a singleton.
8625 ##### Exception
8627 An immutable (`const`) global does not introduce the problems we try to avoid by banning global objects.
8629 ##### Enforcement
8631 (??? NM: Obviously we can warn about non-`const` statics ... do we want to?)
8633 ## <a name="SS-alloc"></a>R.alloc: Allocation and deallocation
8635 ### <a name="Rr-mallocfree"></a>R.10: Avoid `malloc()` and `free()`
8637 ##### Reason
8639  `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`.
8641 ##### Example
8643     class Record {
8644         int id;
8645         string name;
8646         // ...
8647     };
8649     void use()
8650     {
8651         // p1 may be nullptr
8652         // *p1 is not initialized; in particular,
8653         // that string isn't a string, but a string-sized bag of bits
8654         Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));
8656         auto p2 = new Record;
8658         // unless an exception is thrown, *p2 is default initialized
8659         auto p3 = new(nothrow) Record;
8660         // p3 may be nullptr; if not, *p3 is default initialized
8662         // ...
8664         delete p1;    // error: cannot delete object allocated by malloc()
8665         free(p2);    // error: cannot free() object allocated by new
8666     }
8668 In some implementations that `delete` and that `free()` might work, or maybe they will cause run-time errors.
8670 ##### Exception
8672 There are applications and sections of code where exceptions are not acceptable.
8673 Some of the best such examples are in life-critical hard real-time code.
8674 Beware that many bans on exception use are based on superstition (bad)
8675 or by concerns for older code bases with unsystematic resource management (unfortunately, but sometimes necessary).
8676 In such cases, consider the `nothrow` versions of `new`.
8678 ##### Enforcement
8680 Flag explicit use of `malloc` and `free`.
8682 ### <a name="Rr-newdelete"></a>R.11: Avoid calling `new` and `delete` explicitly
8684 ##### Reason
8686 The pointer returned by `new` should belong to a resource handle (that can call `delete`).
8687 If the pointer returned by `new` is assigned to a plain/naked pointer, the object can be leaked.
8689 ##### Note
8691 In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management)
8692 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?
8693 The bug may be latent: it may emerge only during maintenance.
8694 If you have a naked `new`, you probably need a naked `delete` somewhere, so you probably have a bug.
8696 ##### Enforcement
8698 (Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead.
8700 ### <a name="Rr-immediate-alloc"></a>R.12: Immediately give the result of an explicit resource allocation to a manager object
8702 ##### Reason
8704 If you don't, an exception or a return may lead to a leak.
8706 ##### Example, bad
8708     void f(const string& name)
8709     {
8710         FILE* f = fopen(name, "r");          // open the file
8711         vector<char> buf(1024);
8712         auto _ = finally([f] { fclose(f); })  // remember to close the file
8713         // ...
8714     }
8716 The allocation of `buf` may fail and leak the file handle.
8718 ##### Example
8720     void f(const string& name)
8721     {
8722         ifstream f{name};   // open the file
8723         vector<char> buf(1024);
8724         // ...
8725     }
8727 The use of the file handle (in `ifstream`) is simple, efficient, and safe.
8729 ##### Enforcement
8731 * Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)
8733 ### <a name="Rr-single-alloc"></a>R.13: Perform at most one explicit resource allocation in a single expression statement
8735 ##### Reason
8737 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.
8739 ##### Example
8741     void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);
8743 This `fun` can be called like this:
8745     // BAD: potential leak
8746     fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d)));
8748 This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments.
8749 In particular, the compiler can interleave execution of the two expressions:
8750 Memory allocation (by calling `operator new`) could be done first for both objects, followed by attempts to call the two `Widget` constructors.
8751 If one of the constructor calls throws an exception, then the other object's memory will never be released!
8753 This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement.
8754 For example:
8756     shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
8757     fun(sp1, new Widget(c, d));
8759 The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:
8761     fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best
8763 Write your own factory wrapper if there is not one already.
8765 ##### Enforcement
8767 * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
8769 ### <a name="Rr-ap"></a>R.14: ??? array vs. pointer parameter
8771 ##### Reason
8773 An array decays to a pointer, thereby losing its size, opening the opportunity for range errors.
8775 ##### Example
8777     ??? what do we recommend: f(int*[]) or f(int**) ???
8779 **Alternative**: Use `span` to preserve size information.
8781 ##### Enforcement
8783 Flag `[]` parameters.
8785 ### <a name="Rr-pair"></a>R.15: Always overload matched allocation/deallocation pairs
8787 ##### Reason
8789 Otherwise you get mismatched operations and chaos.
8791 ##### Example
8793     class X {
8794         // ...
8795         void* operator new(size_t s);
8796         void operator delete(void*);
8797         // ...
8798     };
8800 ##### Note
8802 If you want memory that cannot be deallocated, `=delete` the deallocation operation.
8803 Don't leave it undeclared.
8805 ##### Enforcement
8807 Flag incomplete pairs.
8809 ## <a name="SS-smart"></a>R.smart: Smart pointers
8811 ### <a name="Rr-owner"></a>R.20: Use `unique_ptr` or `shared_ptr` to represent ownership
8813 ##### Reason
8815 They can prevent resource leaks.
8817 ##### Example
8819 Consider:
8821     void f()
8822     {
8823         X x;
8824         X* p1 { new X };              // see also ???
8825         unique_ptr<T> p2 { new X };   // unique ownership; see also ???
8826         shared_ptr<T> p3 { new X };   // shared ownership; see also ???
8827     }
8829 This will leak the object used to initialize `p1` (only).
8831 ##### Enforcement
8833 (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
8835 ### <a name="Rr-unique"></a>R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership
8837 ##### Reason
8839 A `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).
8841 ##### Example, bad
8843 This needlessly adds and maintains a reference count.
8845     void f()
8846     {
8847         shared_ptr<Base> base = make_shared<Derived>();
8848         // use base locally, without copying it -- refcount never exceeds 1
8849     } // destroy base
8851 ##### Example
8853 This is more efficient:
8855     void f()
8856     {
8857         unique_ptr<Base> base = make_unique<Derived>();
8858         // use base locally
8859     } // destroy base
8861 ##### Enforcement
8863 (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.
8865 ### <a name="Rr-make_shared"></a>R.22: Use `make_shared()` to make `shared_ptr`s
8867 ##### Reason
8869 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.
8871 ##### Example
8873 Consider:
8875     shared_ptr<X> p1 { new X{2} }; // bad
8876     auto p = make_shared<X>(2);    // good
8878 The `make_shared()` version mentions `X` only once, so it is usually shorter (as well as faster) than the version with the explicit `new`.
8880 ##### Enforcement
8882 (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`.
8884 ### <a name="Rr-make_unique"></a>R.23: Use `make_unique()` to make `unique_ptr`s
8886 ##### Reason
8888 For convenience and consistency with `shared_ptr`.
8890 ##### Note
8892 `make_unique()` is C++14, but widely available (as well as simple to write).
8894 ##### Enforcement
8896 (Simple) Warn if a `unique_ptr` is constructed from the result of `new` rather than `make_unique`.
8898 ### <a name="Rr-weak_ptr"></a>R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s
8900 ##### Reason
8902  `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
8903 be able to destroy a cyclic structure.
8905 ##### Example
8907     ???
8909 ##### Note
8911  ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.)
8912 ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it.
8913 You could "temporarily share ownership" simply by using another `shared_ptr`.)
8915 ##### Enforcement
8917 ??? probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr`
8919 ### <a name="Rr-smartptrparam"></a>R.30: Take smart pointers as parameters only to explicitly express lifetime semantics
8921 ##### Reason
8923 Accepting a smart pointer to a `widget` is wrong if the function just needs the `widget` itself.
8924 It should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
8925 A function that does not manipulate lifetime should take raw pointers or references instead.
8927 ##### Example, bad
8929     // callee
8930     void f(shared_ptr<widget>& w)
8931     {
8932         // ...
8933         use(*w); // only use of w -- the lifetime is not used at all
8934         // ...
8935     };
8937     // caller
8938     shared_ptr<widget> my_widget = /* ... */;
8939     f(my_widget);
8941     widget stack_widget;
8942     f(stack_widget); // error
8944 ##### Example, good
8946     // callee
8947     void f(widget& w)
8948     {
8949         // ...
8950         use(w);
8951         // ...
8952     };
8954     // caller
8955     shared_ptr<widget> my_widget = /* ... */;
8956     f(*my_widget);
8958     widget stack_widget;
8959     f(stack_widget); // ok -- now this works
8961 ##### Enforcement
8963 * (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()`.
8964   Suggest using a `T*` or `T&` instead.
8965 * 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.
8966   Suggest using a `T*` or `T&` instead.
8968 ### <a name="Rr-smart"></a>R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`
8970 ##### Reason
8972 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.
8973 You want the rules to work on all the smart pointers you use.
8975 Any type (including primary template or specialization) that overloads unary `*` and `->` is considered a smart pointer:
8977 * If it is copyable, it is recognized as a reference-counted `shared_ptr`.
8978 * If it is not copyable, it is recognized as a unique `unique_ptr`.
8980 ##### Example
8982     // use Boost's intrusive_ptr
8983     #include <boost/intrusive_ptr.hpp>
8984     void f(boost::intrusive_ptr<widget> p)  // error under rule 'sharedptrparam'
8985     {
8986         p->foo();
8987     }
8989     // use Microsoft's CComPtr
8990     #include <atlbase.h>
8991     void f(CComPtr<widget> p)               // error under rule 'sharedptrparam'
8992     {
8993         p->foo();
8994     }
8996 Both cases are an error under the [`sharedptrparam` guideline](#Rr-smartptrparam):
8997 `p` is a `Shared_ptr`, but nothing about its sharedness is used here and passing it by value is a silent pessimization;
8998 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&`.
8999 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.
9001 ### <a name="Rr-uniqueptrparam"></a>R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`
9003 ##### Reason
9005 Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer.
9007 ##### Example
9009     void sink(unique_ptr<widget>); // consumes the widget
9011     void uses(widget*);            // just uses the widget
9013 ##### Example, bad
9015     void thinko(const unique_ptr<widget>&); // usually not what you want
9017 ##### Enforcement
9019 * (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.
9020 * (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.
9022 ### <a name="Rr-reseat"></a>R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the`widget`
9024 ##### Reason
9026 Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics.
9028 ##### Note
9030 "reseat" means "making a pointer or a smart pointer refer to a different object."
9032 ##### Example
9034     void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer
9036 ##### Example, bad
9038     void thinko(const unique_ptr<widget>&); // usually not what you want
9040 ##### Enforcement
9042 * (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.
9043 * (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.
9045 ### <a name="Rr-sharedptrparam-owner"></a>R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner
9047 ##### Reason
9049 This makes the function's ownership sharing explicit.
9051 ##### Example, good
9053     void share(shared_ptr<widget>);            // share -- "will" retain refcount
9055     void may_share(const shared_ptr<widget>&); // "might" retain refcount
9057     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
9059 ##### Enforcement
9061 * (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.
9062 * (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.
9063 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
9065 ### <a name="Rr-sharedptrparam"></a>R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer
9067 ##### Reason
9069 This makes the function's reseating explicit.
9071 ##### Note
9073 "reseat" means "making a reference or a smart pointer refer to a different object."
9075 ##### Example, good
9077     void share(shared_ptr<widget>);            // share -- "will" retain refcount
9079     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
9081     void may_share(const shared_ptr<widget>&); // "might" retain refcount
9083 ##### Enforcement
9085 * (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.
9086 * (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.
9087 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
9089 ### <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 ???
9091 ##### Reason
9093 This makes the function's ??? explicit.
9095 ##### Example, good
9097     void share(shared_ptr<widget>);            // share -- "will" retain refcount
9099     void reseat(shared_ptr<widget>&);          // "might" reseat ptr
9101     void may_share(const shared_ptr<widget>&); // "might" retain refcount
9103 ##### Enforcement
9105 * (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.
9106 * (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.
9107 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
9109 ### <a name="Rr-smartptrget"></a>R.37: Do not pass a pointer or reference obtained from an aliased smart pointer
9111 ##### Reason
9113 Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer.
9114 Functions should prefer to pass raw pointers and references down call chains.
9115 At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive.
9116 You need to be sure that the smart pointer cannot inadvertently be reset or reassigned from within the call tree below.
9118 ##### Note
9120 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.
9122 ##### Example
9124 Consider this code:
9126     // global (static or heap), or aliased local ...
9127     shared_ptr<widget> g_p = ...;
9129     void f(widget& w)
9130     {
9131         g();
9132         use(w);  // A
9133     }
9135     void g()
9136     {
9137         g_p = ...; // oops, if this was the last shared_ptr to that widget, destroys the widget
9138     }
9140 The following should not pass code review:
9142     void my_code()
9143     {
9144         // BAD: passing pointer or reference obtained from a nonlocal smart pointer
9145         //      that could be inadvertently reset somewhere inside f or it callees
9146         f(*g_p);
9148         // BAD: same reason, just passing it as a "this" pointer
9149          g_p->func();
9150     }
9152 The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:
9154     void my_code()
9155     {
9156         // cheap: 1 increment covers this entire function and all the call trees below us
9157         auto pin = g_p;
9159         // GOOD: passing pointer or reference obtained from a local unaliased smart pointer
9160         f(*pin);
9162         // GOOD: same reason
9163         pin->func();
9164     }
9166 ##### Enforcement
9168 * (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.
9170 # <a name="S-expr"></a>ES: Expressions and Statements
9172 Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements.
9174 For naming, commenting, and indentation rules, see [NL: Naming and layout](#S-naming).
9176 General rules:
9178 * [ES.1: Prefer the standard library to other libraries and to "handcrafted code"](#Res-lib)
9179 * [ES.2: Prefer suitable abstractions to direct use of language features](#Res-abstr)
9181 Declaration rules:
9183 * [ES.5: Keep scopes small](#Res-scope)
9184 * [ES.6: Declare names in for-statement initializers and conditions to limit scope](#Res-cond)
9185 * [ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer](#Res-name-length)
9186 * [ES.8: Avoid similar-looking names](#Res-name-similar)
9187 * [ES.9: Avoid `ALL_CAPS` names](#Res-not-CAPS)
9188 * [ES.10: Declare one name (only) per declaration](#Res-name-one)
9189 * [ES.11: Use `auto` to avoid redundant repetition of type names](#Res-auto)
9190 * [ES.12: Do not reuse names in nested scopes](#Res-reuse)
9191 * [ES.20: Always initialize an object](#Res-always)
9192 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
9193 * [ES.22: Don't declare a variable until you have a value to initialize it with](#Res-init)
9194 * [ES.23: Prefer the `{}`-initializer syntax](#Res-list)
9195 * [ES.24: Use a `unique_ptr<T>` to hold pointers in code that may throw](#Res-unique)
9196 * [ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on](#Res-const)
9197 * [ES.26: Don't use a variable for two unrelated purposes](#Res-recycle)
9198 * [ES.27: Use `std::array` or `stack_array` for arrays on the stack](#Res-stack)
9199 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
9200 * [ES.30: Don't use macros for program text manipulation](#Res-macros)
9201 * [ES.31: Don't use macros for constants or "functions"](#Res-macros2)
9202 * [ES.32: Use `ALL_CAPS` for all macro names](#Res-ALL_CAPS)
9203 * [ES.33: If you must use macros, give them unique names](#Res-MACROS)
9204 * [ES.34: Don't define a (C-style) variadic function](#Res-ellipses)
9206 Expression rules:
9208 * [ES.40: Avoid complicated expressions](#Res-complicated)
9209 * [ES.41: If in doubt about operator precedence, parenthesize](#Res-parens)
9210 * [ES.42: Keep use of pointers simple and straightforward](#Res-ptr)
9211 * [ES.43: Avoid expressions with undefined order of evaluation](#Res-order)
9212 * [ES.44: Don't depend on order of evaluation of function arguments](#Res-order-fct)
9213 * [ES.45: Avoid narrowing conversions](#Res-narrowing)
9214 * [ES.46: Avoid "magic constants"; use symbolic constants](#Res-magic)
9215 * [ES.47: Use `nullptr` rather than `0` or `NULL`](#Res-nullptr)
9216 * [ES.48: Avoid casts](#Res-casts)
9217 * [ES.49: If you must use a cast, use a named cast](#Res-casts-named)
9218 * [ES.50: Don't cast away `const`](#Res-casts-const)
9219 * [ES.55: Avoid the need for range checking](#Res-range-checking)
9220 * [ES.56: Write `std::move()` only when you need to explicitly move an object to another scope](#Res-move)
9221 * [ES.60: Avoid `new` and `delete` outside resource management functions](#Res-new)
9222 * [ES.61: Delete arrays using `delete[]` and non-arrays using `delete`](#Res-del)
9223 * [ES.62: Don't compare pointers into different arrays](#Res-arr2)
9224 * [ES.63: Don't slice](#Res-slice)
9226 Statement rules:
9228 * [ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice](#Res-switch-if)
9229 * [ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice](#Res-for-range)
9230 * [ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable](#Res-for-while)
9231 * [ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable](#Res-while-for)
9232 * [ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement](#Res-for-init)
9233 * [ES.75: Avoid `do`-statements](#Res-do)
9234 * [ES.76: Avoid `goto`](#Res-goto)
9235 * [ES.77: Minimize the use of `break` and `continue` in loops](#Res-continue)
9236 * [ES.78: Always end a non-empty `case` with a `break`](#Res-break)
9237 * [ES.79: Use `default` to handle common cases (only)](#Res-default)
9238 * [ES.84: Don't (try to) declare a local variable with no name](#Res-noname)
9239 * [ES.85: Make empty statements visible](#Res-empty)
9240 * [ES.86: Avoid modifying loop control variables inside the body of raw for-loops](#Res-loop-counter)
9242 Arithmetic rules:
9244 * [ES.100: Don't mix signed and unsigned arithmetic](#Res-mix)
9245 * [ES.101: Use unsigned types for bit manipulation](#Res-unsigned)
9246 * [ES.102: Use signed types for arithmetic](#Res-signed)
9247 * [ES.103: Don't overflow](#Res-overflow)
9248 * [ES.104: Don't underflow](#Res-underflow)
9249 * [ES.105: Don't divide by zero](#Res-zero)
9251 ### <a name="Res-lib"></a>ES.1: Prefer the standard library to other libraries and to "handcrafted code"
9253 ##### Reason
9255 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.
9256 The ISO C++ standard library is among the most widely known and best tested libraries.
9257 It is available as part of all C++ Implementations.
9259 ##### Example
9261     auto sum = accumulate(begin(a), end(a), 0.0);   // good
9263 a range version of `accumulate` would be even better:
9265     auto sum = accumulate(v, 0.0); // better
9267 but don't hand-code a well-known algorithm:
9269     int max = v.size();   // bad: verbose, purpose unstated
9270     double sum = 0.0;
9271     for (int i = 0; i < max; ++i)
9272         sum = sum + v[i];
9274 ##### Exception
9276 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.
9278 ##### Enforcement
9280 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
9282 ### <a name="Res-abstr"></a>ES.2: Prefer suitable abstractions to direct use of language features
9284 ##### Reason
9286 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.
9288 ##### Example
9290     vector<string> read1(istream& is)   // good
9291     {
9292         vector<string> res;
9293         for (string s; is >> s;)
9294             res.push_back(s);
9295         return res;
9296     }
9298 The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:
9300     char** read2(istream& is, int maxelem, int maxstring, int* nread)   // bad: verbose and incomplete
9301     {
9302         auto res = new char*[maxelem];
9303         int elemcount = 0;
9304         while (is && elemcount < maxelem) {
9305             auto s = new char[maxstring];
9306             is.read(s, maxstring);
9307             res[elemcount++] = s;
9308         }
9309         nread = &elemcount;
9310         return res;
9311     }
9313 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.
9315 ##### Enforcement
9317 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
9319 ## ES.dcl: Declarations
9321 A declaration is a statement. A declaration introduces a name into a scope and may cause the construction of a named object.
9323 ### <a name="Res-scope"></a>ES.5: Keep scopes small
9325 ##### Reason
9327 Readability. Minimize resource retention. Avoid accidental misuse of value.
9329 **Alternative formulation**: Don't declare a name in an unnecessarily large scope.
9331 ##### Example
9333     void use()
9334     {
9335         int i;    // bad: i is needlessly accessible after loop
9336         for (i = 0; i < 20; ++i) { /* ... */ }
9337         // no intended use of i here
9338         for (int i = 0; i < 20; ++i) { /* ... */ }  // good: i is local to for-loop
9340         if (auto pc = dynamic_cast<Circle*>(ps)) {  // good: pc is local to if-statement
9341             // ... deal with Circle ...
9342         }
9343         else {
9344             // ... handle error ...
9345         }
9346     }
9348 ##### Example, bad
9350     void use(const string& name)
9351     {
9352         string fn = name + ".txt";
9353         ifstream is {fn};
9354         Record r;
9355         is >> r;
9356         // ... 200 lines of code without intended use of fn or is ...
9357     }
9359 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`
9360 are retained for much longer than needed and that unanticipated use of `is` and `fn` could happen later in the function.
9361 In this case, it might be a good idea to factor out the read:
9363     Record load_record(const string& name)
9364     {
9365         string fn = name + ".txt";
9366         ifstream is {fn};
9367         Record r;
9368         is >> r;
9369         return r;
9370     }
9372     void use(const string& name)
9373     {
9374         Record r = load_record(name);
9375         // ... 200 lines of code ...
9376     }
9378 ##### Enforcement
9380 * Flag loop variable declared outside a loop and not used after the loop
9381 * Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
9383 ### <a name="Res-cond"></a>ES.6: Declare names in for-statement initializers and conditions to limit scope
9385 ##### Reason
9387 Readability. Minimize resource retention.
9389 ##### Example
9391     void use()
9392     {
9393         for (string s; cin >> s;)
9394             v.push_back(s);
9396         for (int i = 0; i < 20; ++i) {   // good: i is local to for-loop
9397             // ...
9398         }
9400         if (auto pc = dynamic_cast<Circle*>(ps)) {   // good: pc is local to if-statement
9401             // ... deal with Circle ...
9402         }
9403         else {
9404             // ... handle error ...
9405         }
9406     }
9408 ##### Enforcement
9410 * Flag loop variables declared before the loop and not used after the loop
9411 * (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
9413 ##### C++17 example
9415 Note: C++17 also adds `if` and `switch` initializer statements. These require C++17 support.
9417     map<int, string> mymap;
9419     if (auto result = mymap.insert(value); result.second) {
9420         // insert succeeded, and result is valid for this block
9421         use(result.first);  // ok
9422         // ...
9423     } // result is destroyed here
9425 ##### C++17 enforcement (if using a C++17 compiler)
9427 * Flag selection/loop variables declared before the body and not used after the body
9428 * (hard) Flag selection/loop variables declared before the body and used after the body for an unrelated purpose.
9432 ### <a name="Res-name-length"></a>ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer
9434 ##### Reason
9436 Readability. Lowering the chance of clashes between unrelated non-local names.
9438 ##### Example
9440 Conventional short, local names increase readability:
9442     template<typename T>    // good
9443     void print(ostream& os, const vector<T>& v)
9444     {
9445         for (int i = 0; i < v.size(); ++i)
9446             os << v[i] << '\n';
9447     }
9449 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
9451     template<typename Element_type>   // bad: verbose, hard to read
9452     void print(ostream& target_stream, const vector<Element_type>& current_vector)
9453     {
9454         for (int current_element_index = 0;
9455                 current_element_index < current_vector.size();
9456                 ++current_element_index
9457         )
9458         target_stream << current_vector[current_element_index] << '\n';
9459     }
9461 Yes, it is a caricature, but we have seen worse.
9463 ##### Example
9465 Unconventional and short non-local names obscure code:
9467     void use1(const string& s)
9468     {
9469         // ...
9470         tt(s);   // bad: what is tt()?
9471         // ...
9472     }
9474 Better, give non-local entities readable names:
9476     void use1(const string& s)
9477     {
9478         // ...
9479         trim_tail(s);   // better
9480         // ...
9481     }
9483 Here, there is a chance that the reader knows what `trim_tail` means and that the reader can remember it after looking it up.
9485 ##### Example, bad
9487 Argument names of large functions are de facto non-local and should be meaningful:
9489     void complicated_algorithm(vector<Record>& vr, const vector<int>& vi, map<string, int>& out)
9490     // read from events in vr (marking used Records) for the indices in
9491     // vi placing (name, index) pairs into out
9492     {
9493         // ... 500 lines of code using vr, vi, and out ...
9494     }
9496 We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.
9498 ##### Enforcement
9500 Check length of local and non-local names. Also take function length into account.
9502 ### <a name="Res-name-similar"></a>ES.8: Avoid similar-looking names
9504 ##### Reason
9506 Code clarity and readability. Too-similar names slow down comprehension and increase the likelihood of error.
9508 ##### Example; bad
9510     if (readable(i1 + l1 + ol + o1 + o0 + ol + o1 + I0 + l0)) surprise();
9512 ##### Example; bad
9514 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.
9516     struct foo { int n; };
9517     struct foo foo();       // BAD, foo is a type already in scope
9518     struct foo x = foo();   // requires disambiguation
9520 ##### Exception
9522 Antique header files might declare non-types and types with the same name in the same scope.
9524 ##### Enforcement
9526 * Check names against a list of known confusing letter and digit combinations.
9527 * Flag a declaration of a variable, function, or enumerator that hides a class or enumeration declared in the same scope.
9529 ### <a name="Res-not-CAPS"></a>ES.9: Avoid `ALL_CAPS` names
9531 ##### Reason
9533 Such names are commonly used for macros. Thus, `ALL_CAPS` name are vulnerable to unintended macro substitution.
9535 ##### Example
9537     // somewhere in some header:
9538     #define NE !=
9540     // somewhere else in some other header:
9541     enum Coord { N, NE, NW, S, SE, SW, E, W };
9543     // somewhere third in some poor programmer's .cpp:
9544     switch (direction) {
9545     case N:
9546         // ...
9547     case NE:
9548         // ...
9549     // ...
9550     }
9552 ##### Note
9554 Do not use `ALL_CAPS` for constants just because constants used to be macros.
9556 ##### Enforcement
9558 Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names.
9560 ### <a name="Res-name-one"></a>ES.10: Declare one name (only) per declaration
9562 ##### Reason
9564 One-declaration-per line increases readability and avoids mistakes related to
9565 the C/C++ grammar. It also leaves room for a more descriptive end-of-line
9566 comment.
9568 ##### Example, bad
9570     char *p, c, a[7], *pp[7], **aa[10];   // yuck!
9572 ##### Exception
9574 A function declaration can contain several function argument declarations.
9576 ##### Exception
9578 A structured binding (C++17) is specifically designed to introduce several variables:
9580     auto [iter, inserted] = m.insert_or_assign(k, val);
9581     if (inserted) { /* new entry was inserted */ }
9583 ##### Example
9585     template <class InputIterator, class Predicate>
9586     bool any_of(InputIterator first, InputIterator last, Predicate pred);
9588 or better using concepts:
9590     bool any_of(InputIterator first, InputIterator last, Predicate pred);
9592 ##### Example
9594     double scalbn(double x, int n);   // OK: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
9598     double scalbn(    // better: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
9599         double x,     // base value
9600         int n         // exponent
9601     );
9605     // better: base * pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
9606     double scalbn(double base, int exponent);
9608 ##### Example
9610     int a = 7, b = 9, c, d = 10, e = 3;
9612 In a long list of declarators is is easy to overlook an uninitialized variable.
9614 ##### Enforcement
9616 Flag variable and constant declarations with multiple declarators (e.g., `int* p, q;`)
9618 ### <a name="Res-auto"></a>ES.11: Use `auto` to avoid redundant repetition of type names
9620 ##### Reason
9622 * Simple repetition is tedious and error prone.
9623 * When you use `auto`, the name of the declared entity is in a fixed position in the declaration, increasing readability.
9624 * In a template function declaration the return type can be a member type.
9626 ##### Example
9628 Consider:
9630     auto p = v.begin();   // vector<int>::iterator
9631     auto s = v.size();
9632     auto h = t.future();
9633     auto q = make_unique<int[]>(s);
9634     auto f = [](int x){ return x + 10; };
9636 In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
9638 ##### Example
9640     template<class T>
9641     auto Container<T>::first() -> Iterator;   // Container<T>::Iterator
9643 ##### Exception
9645 Avoid `auto` for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.
9647 ##### Example
9649     auto lst = { 1, 2, 3 };   // lst is an initializer list
9650     auto x{1};   // x is an int (after correction of the C++14 standard; initializer_list in C++11)
9652 ##### Note
9654 When concepts become available, we can (and should) be more specific about the type we are deducing:
9656     // ...
9657     ForwardIterator p = algo(x, y, z);
9659 ##### Example (C++17)
9660     
9661     auto [ quotient, remainder ] = div(123456, 73);   // break out the members of the div_t result
9663 ##### Enforcement
9665 Flag redundant repetition of type names in a declaration.
9667 ### <a name="Res-reuse"></a>ES.12: Do not reuse names in nested scopes
9669 ##### Reason
9671 It is easy to get confused about which variable is used.
9672 Can cause maintenance problems.
9674 ##### Example, bad
9676     int d = 0;
9677     // ...
9678     if (cond) {
9679         // ...
9680         d = 9;
9681         // ...
9682     }
9683     else {
9684         // ...
9685         int d = 7;
9686         // ...
9687         d = value_to_be_returned;
9688         // ...
9689     }
9691     return d;
9693 If this is a large `if`-statement, it is easy to overlook that a new `d` has been introduced in the inner scope.
9694 This is a known source of bugs.
9695 Sometimes such reuse of a name in an inner scope is called "shadowing".
9697 ##### Note
9699 Shadowing is primarily a problem when functions are too large and too complex.
9701 ##### Example
9703 Shadowing of function arguments in the outermost block is disallowed by the language:
9705     void f(int x)
9706     {
9707         int x = 4;  // error: reuse of function argument name
9709         if (x) {
9710             int x = 7;  // allowed, but bad
9711             // ...
9712         }
9713     }
9715 ##### Example, bad
9717 Reuse of a member name as a local variable can also be a problem:
9719     struct S {
9720         int m;
9721         void f(int x);
9722     };
9724     void S::f(int x)
9725     {
9726         m = 7;    // assign to member
9727         if (x) {
9728             int m = 9;
9729             // ...
9730             m = 99; // assign to member
9731             // ...
9732         }
9733     }
9735 ##### Exception
9737 We often reuse function names from a base class in a derived class:
9739     struct B {
9740         void f(int);
9741     };
9743     struct D : B {
9744         void f(double);
9745         using B::f;
9746     };
9748 This is error-prone.
9749 For example, had we forgotten the using declaration, a call `d.f(1)` would not have found the `int` version of `f`.
9751 ??? Do we need a specific rule about shadowing/hiding in class hierarchies?
9753 ##### Enforcement
9755 * Flag reuse of a name in nested local scopes
9756 * Flag reuse of a member name as a local variable in a member function
9757 * Flag reuse of a global name as a local variable or a member name
9758 * Flag reuse of a base class member name in a derived class (except for function names)
9760 ### <a name="Res-always"></a>ES.20: Always initialize an object
9762 ##### Reason
9764 Avoid used-before-set errors and their associated undefined behavior.
9765 Avoid problems with comprehension of complex initialization.
9766 Simplify refactoring.
9768 ##### Example
9770     void use(int arg)
9771     {
9772         int i;   // bad: uninitialized variable
9773         // ...
9774         i = 7;   // initialize i
9775     }
9777 No, `i = 7` does not initialize `i`; it assigns to it. Also, `i` can be read in the `...` part. Better:
9779     void use(int arg)   // OK
9780     {
9781         int i = 7;   // OK: initialized
9782         string s;    // OK: default initialized
9783         // ...
9784     }
9786 ##### Note
9788 The *always initialize* rule is deliberately stronger than the *an object must be set before used* language rule.
9789 The latter, more relaxed rule, catches the technical bugs, but:
9791 * It leads to less readable code
9792 * It encourages people to declare names in greater than necessary scopes
9793 * It leads to harder to read code
9794 * It leads to logic bugs by encouraging complex code
9795 * It hampers refactoring
9797 The *always initialize* rule is a style rule aimed to improve maintainability as well as a rule protecting against used-before-set errors.
9799 ##### Example
9801 Here is an example that is often considered to demonstrate the need for a more relaxed rule for initialization
9803     widget i;    // "widget" a type that's expensive to initialize, possibly a large POD
9804     widget j;
9806     if (cond) {  // bad: i and j are initialized "late"
9807         i = f1();
9808         j = f2();
9809     }
9810     else {
9811         i = f3();
9812         j = f4();
9813     }
9815 This cannot trivially be rewritten to initialize `i` and `j` with initializers.
9816 Note that for types with a default constructor, attempting to postpone initialization simply leads to a default initialization followed by an assignment.
9817 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.
9819 At the cost of repeating `cond` we could write:
9821     widget i = (cond) ? f1() : f3();
9822     widget j = (cond) ? f2() : f4();
9824 Assuming that there is a logical connection between `i` and `j`, that connection should probably be expressed in code:
9826     pair<widget, widget> make_related_widgets(bool x)
9827     {
9828         return (x) ? {f1(), f2()} : {f3(), f4() };
9829     }
9831     auto init = make_related_widgets(cond);
9832     widget i = init.first;
9833     widget j = init.second;
9835 Obviously, what we really would like is a construct that initialized n variables from a `tuple`. For example:
9837     auto [i, j] = make_related_widgets(cond);    // C++17, not C++14
9839 Today, we might approximate that using `tie()`:
9841     widget i;       // bad: uninitialized variable
9842     widget j;
9843     tie(i, j) = make_related_widgets(cond);
9845 This may be seen as an example of the *immediately initialize from input* exception below.
9847 Creating optimal and equivalent code from all of these examples should be well within the capabilities of modern C++ compilers
9848 (but don't make performance claims without measuring; a compiler may very well not generate optimal code for every example and
9849 there may be language rules preventing some optimization that you would have liked in a particular case).
9851 ##### Note
9853 Complex initialization has been popular with clever programmers for decades.
9854 It has also been a major source of errors and complexity.
9855 Many such errors are introduced during maintenance years after the initial implementation.
9857 ##### Exception
9859 It you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization.
9860 However, beware that this may leave uninitialized data beyond the input -- and that has been a fertile source of errors and security breaches:
9862     constexpr int max = 8 * 1024;
9863     int buf[max];         // OK, but suspicious: uninitialized
9864     f.read(buf, max);
9866 The cost of initializing that array could be significant in some situations.
9867 However, such examples do tend to leave uninitialized variables accessible, so they should be treated with suspicion.
9869     constexpr int max = 8 * 1024;
9870     int buf[max] = {};   // zero all elements; better in some situations
9871     f.read(buf, max);
9873 When feasible use a library function that is known not to overflow. For example:
9875     string s;   // s is default initialized to ""
9876     cin >> s;   // s expands to hold the string
9878 Don't consider simple variables that are targets for input operations exceptions to this rule:
9880     int i;   // bad
9881     // ...
9882     cin >> i;
9884 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.
9886     int i2 = 0;   // better
9887     // ...
9888     cin >> i;
9890 A good optimizer should know about input operations and eliminate the redundant operation.
9892 ##### Example
9894 Using an `uninitialized` or sentinel value is a symptom of a problem and not a
9895 solution:
9897     widget i = uninit;  // bad
9898     widget j = uninit;
9900     // ...
9901     use(i);         // possibly used before set
9902     // ...
9904     if (cond) {     // bad: i and j are initialized "late"
9905         i = f1();
9906         j = f2();
9907     }
9908     else {
9909         i = f3();
9910         j = f4();
9911     }
9913 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?
9915 ##### Note
9917 Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable:
9919     error_code ec;
9920     Value v = [&] {
9921         auto p = get_value();   // get_value() returns a pair<error_code, Value>
9922         ec = p.first;
9923         return p.second;
9924     }();
9926 or maybe:
9928     Value v = [] {
9929         auto p = get_value();   // get_value() returns a pair<error_code, Value>
9930         if (p.first) throw Bad_value{p.first};
9931         return p.second;
9932     }();
9934 **See also**: [ES.28](#Res-lambda-init)
9936 ##### Enforcement
9938 * Flag every uninitialized variable.
9939   Don't flag variables of user-defined types with default constructors.
9940 * Check that an uninitialized buffer is written into *immediately* after declaration.
9941   Passing an uninitialized variable as a reference to non-`const` argument can be assumed to be a write into the variable.
9943 ### <a name="Res-introduce"></a>ES.21: Don't introduce a variable (or constant) before you need to use it
9945 ##### Reason
9947 Readability. To limit the scope in which the variable can be used.
9949 ##### Example
9951     int x = 7;
9952     // ... no use of x here ...
9953     ++x;
9955 ##### Enforcement
9957 Flag declarations that are distant from their first use.
9959 ### <a name="Res-init"></a>ES.22: Don't declare a variable until you have a value to initialize it with
9961 ##### Reason
9963 Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment.
9965 ##### Example, bad
9967     string s;
9968     // ... no use of s here ...
9969     s = "what a waste";
9971 ##### Example, bad
9973     SomeLargeType var;   // ugly CaMeLcAsEvArIaBlE
9975     if (cond)   // some non-trivial condition
9976         Set(&var);
9977     else if (cond2 || !cond3) {
9978         var = Set2(3.14);
9979     }
9980     else {
9981         var = 0;
9982         for (auto& e : something)
9983             var += e;
9984     }
9986     // use var; that this isn't done too early can be enforced statically with only control flow
9988 This would be fine if there was a default initialization for `SomeLargeType` that wasn't too expensive.
9989 Otherwise, a programmer might very well wonder if every possible path through the maze of conditions has been covered.
9990 If not, we have a "use before set" bug. This is a maintenance trap.
9992 For initializers of moderate complexity, including for `const` variables, consider using a lambda to express the initializer; see [ES.28](#Res-lambda-init).
9994 ##### Enforcement
9996 * Flag declarations with default initialization that are assigned to before they are first read.
9997 * Flag any complicated computation after an uninitialized variable and before its use.
9999 ### <a name="Res-list"></a>ES.23: Prefer the `{}` initializer syntax
10001 ##### Reason
10003 The rules for `{}` initialization are simpler, more general, less ambiguous, and safer than for other forms of initialization.
10005 ##### Example
10007     int x {f(99)};
10008     vector<int> v = {1, 2, 3, 4, 5, 6};
10010 ##### Exception
10012 For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes:
10014     vector<int> v1(10);    // vector of 10 elements with the default value 0
10015     vector<int> v2 {10};   // vector of 1 element with the value 10
10017 ##### Note
10019 `{}`-initializers do not allow narrowing conversions.
10021 ##### Example
10023     int x {7.9};   // error: narrowing
10024     int y = 7.9;   // OK: y becomes 7. Hope for a compiler warning
10026 ##### Note
10028 `{}` initialization can be used for all initialization; other forms of initialization can't:
10030     auto p = new vector<int> {1, 2, 3, 4, 5};   // initialized vector
10031     D::D(int a, int b) :m{a, b} {   // member initializer (e.g., m might be a pair)
10032         // ...
10033     };
10034     X var {};   // initialize var to be empty
10035     struct S {
10036         int m {7};   // default initializer for a member
10037         // ...
10038     };
10040 ##### Note
10042 Initialization of a variable declared using `auto` with a single value, e.g., `{v}`, had surprising results until C++17.
10043 The C++17 rules are somewhat less surprising:
10045     auto x1 {7};        // x1 is an int with the value 7
10046     auto x2 = {7};  // x2 is an initializer_list<int> with an element 7
10048     auto x11 {7, 8};    // error: two initializers
10049     auto x22 = {7, 8};  // x2 is an initializer_list<int> with elements 7 and 8
10051 So use `={...}` if you really want an `initializer_list<T>`
10053     auto fib10 = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55};   // fib10 is a list
10055 ##### Note
10057 Old habits die hard, so this rule is hard to apply consistently, especially as there are so many cases where `=` is innocent.
10059 ##### Example
10061     template<typename T>
10062     void f()
10063     {
10064         T x1(1);    // T initialized with 1
10065         T x0();     // bad: function declaration (often a mistake)
10067         T y1 {1};   // T initialized with 1
10068         T y0 {};    // default initialized T
10069         // ...
10070     }
10072 **See also**: [Discussion](#???)
10074 ##### Enforcement
10076 Tricky.
10078 * Don't flag uses of `=` for simple initializers.
10079 * Look for `=` after `auto` has been seen.
10081 ### <a name="Res-unique"></a>ES.24: Use a `unique_ptr<T>` to hold pointers
10083 ##### Reason
10085 Using `std::unique_ptr` is the simplest way to avoid leaks. It is reliable, it
10086 makes the type system do much of the work to validate ownership safety, it
10087 increases readability, and it has zero or near zero runtime cost.
10089 ##### Example
10091     void use(bool leak)
10092     {
10093         auto p1 = make_unique<int>(7);   // OK
10094         int* p2 = new int{7};            // bad: might leak
10095         // ... no assignment to p2 ...
10096         if (leak) return;
10097         // ... no assignment to p2 ...
10098         vector<int> v(7);
10099         v.at(7) = 0;                    // exception thrown
10100         // ...
10101     }
10103 If `leak == true` the object pointed to by `p2` is leaked and the object pointed to by `p1` is not.
10104 The same is the case when `at()` throws.
10106 ##### Enforcement
10108 Look for raw pointers that are targets of `new`, `malloc()`, or functions that may return such pointers.
10110 ### <a name="Res-const"></a>ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on
10112 ##### Reason
10114 That way you can't change the value by mistake. That way may offer the compiler optimization opportunities.
10116 ##### Example
10118     void f(int n)
10119     {
10120         const int bufmax = 2 * n + 2;  // good: we can't change bufmax by accident
10121         int xmax = n;                  // suspicious: is xmax intended to change?
10122         // ...
10123     }
10125 ##### Enforcement
10127 Look to see if a variable is actually mutated, and flag it if
10128 not. Unfortunately, it may be impossible to detect when a non-`const` was not
10129 *intended* to vary (vs when it merely did not vary).
10131 ### <a name="Res-recycle"></a>ES.26: Don't use a variable for two unrelated purposes
10133 ##### Reason
10135 Readability and safety.
10137 ##### Example, bad
10139     void use()
10140     {
10141         int i;
10142         for (i = 0; i < 20; ++i) { /* ... */ }
10143         for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled
10144     }
10146 ##### Note
10148 As an optimization, you may want to reuse a buffer as a scratch pad, but even then prefer to limit the variable's scope as much as possible and be careful not to cause bugs from data left in a recycled buffer as this is a common source of security bugs.
10150     {
10151         std::string buffer;             // to avoid reallocations on every loop iteration
10152         for (auto& o : objects)
10153         {
10154             // First part of the work.
10155             generateFirstString(buffer, o);
10156             writeToFile(buffer);
10158             // Second part of the work.
10159             generateSecondString(buffer, o);
10160             writeToFile(buffer);
10162             // etc...
10163         }
10164     }
10166 ##### Enforcement
10168 Flag recycled variables.
10170 ### <a name="Res-stack"></a>ES.27: Use `std::array` or `stack_array` for arrays on the stack
10172 ##### Reason
10174 They are readable and don't implicitly convert to pointers.
10175 They are not confused with non-standard extensions of built-in arrays.
10177 ##### Example, bad
10179     const int n = 7;
10180     int m = 9;
10182     void f()
10183     {
10184         int a1[n];
10185         int a2[m];   // error: not ISO C++
10186         // ...
10187     }
10189 ##### Note
10191 The definition of `a1` is legal C++ and has always been.
10192 There is a lot of such code.
10193 It is error-prone, though, especially when the bound is non-local.
10194 Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.).
10195 The definition of `a2` is C but not C++ and is considered a security risk
10197 ##### Example
10199     const int n = 7;
10200     int m = 9;
10202     void f()
10203     {
10204         array<int, n> a1;
10205         stack_array<int> a2(m);
10206         // ...
10207     }
10209 ##### Enforcement
10211 * Flag arrays with non-constant bounds (C-style VLAs)
10212 * Flag arrays with non-local constant bounds
10214 ### <a name="Res-lambda-init"></a>ES.28: Use lambdas for complex initialization, especially of `const` variables
10216 ##### Reason
10218 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.
10220 ##### Example, bad
10222     widget x;   // should be const, but:
10223     for (auto i = 2; i <= N; ++i) {             // this could be some
10224         x += some_obj.do_something_with(i);  // arbitrarily long code
10225     }                                        // needed to initialize x
10226     // from here, x should be const, but we can't say so in code in this style
10228 ##### Example, good
10230     const widget x = [&]{
10231         widget val;                                // assume that widget has a default constructor
10232         for (auto i = 2; i <= N; ++i) {            // this could be some
10233             val += some_obj.do_something_with(i);  // arbitrarily long code
10234         }                                          // needed to initialize x
10235         return val;
10236     }();
10238 ##### Example
10240     string var = [&]{
10241         if (!in) return "";   // default
10242         string s;
10243         for (char c : in >> c)
10244             s += toupper(c);
10245         return s;
10246     }(); // note ()
10248 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.
10250 ##### Example
10252     bool owned = false;
10253     owner<istream*> inp = [&]{
10254         switch (source) {
10255         case default:       owned = false; return &cin;
10256         case command_line:  owned = true;  return new istringstream{argv[2]};
10257         case file:          owned = true;  return new ifstream{argv[2]};
10258     }();
10259     istream& in = *inp;
10261 ##### Enforcement
10263 Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.
10265 ### <a name="Res-macros"></a>ES.30: Don't use macros for program text manipulation
10267 ##### Reason
10269 Macros are a major source of bugs.
10270 Macros don't obey the usual scope and type rules.
10271 Macros ensure that the human reader sees something different from what the compiler sees.
10272 Macros complicate tool building.
10274 ##### Example, bad
10276     #define Case break; case   /* BAD */
10278 This innocuous-looking macro makes a single lower case `c` instead of a `C` into a bad flow-control bug.
10280 ##### Note
10282 This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc.
10284 ##### Enforcement
10286 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
10288 ### <a name="Res-macros2"></a>ES.31: Don't use macros for constants or "functions"
10290 ##### Reason
10292 Macros are a major source of bugs.
10293 Macros don't obey the usual scope and type rules.
10294 Macros don't obey the usual rules for argument passing.
10295 Macros ensure that the human reader sees something different from what the compiler sees.
10296 Macros complicate tool building.
10298 ##### Example, bad
10300     #define PI 3.14
10301     #define SQUARE(a, b) (a * b)
10303 Even if we hadn't left a well-known bug in `SQUARE` there are much better behaved alternatives; for example:
10305     constexpr double pi = 3.14;
10306     template<typename T> T square(T a, T b) { return a * b; }
10308 ##### Enforcement
10310 Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`)
10312 ### <a name="Res-ALL_CAPS"></a>ES.32: Use `ALL_CAPS` for all macro names
10314 ##### Reason
10316 Convention. Readability. Distinguishing macros.
10318 ##### Example
10320     #define forever for (;;)   /* very BAD */
10322     #define FOREVER for (;;)   /* Still evil, but at least visible to humans */
10324 ##### Enforcement
10326 Scream when you see a lower case macro.
10328 ### <a name="Res-MACROS"></a>ES.33: If you must use macros, give them unique names
10330 ##### Reason
10332 Macros do not obey scope rules.
10334 ##### Example
10336     #define MYCHAR        /* BAD, will eventually clash with someone else's MYCHAR*/
10338     #define ZCORP_CHAR    /* Still evil, but less likely to clash */
10340 ##### Note
10342 Avoid macros if you can: [ES.30](#Res-macros), [ES.31](#Res-macros2), and [ES.32](#Res-ALL_CAPS).
10343 However, there are billions of lines of code littered with macros and a long tradition for using and overusing macros.
10344 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.
10346 ##### Enforcement
10348 Warn against short macro names.
10350 ### <a name="Res-ellipses"></a> ES.34: Don't define a (C-style) variadic function
10352 ##### Reason
10354 Not type safe.
10355 Requires messy cast-and-macro-laden code to get working right.
10357 ##### Example
10359     #include <cstdarg>
10361     // "severity" followed by a zero-terminated list of char*s; write the C-style strings to cerr
10362     void error(int severity ...)
10363     {
10364         va_list ap;             // a magic type for holding arguments
10365         va_start(ap, severity); // arg startup: "severity" is the first argument of error()
10367         for (;;) {
10368             // treat the next var as a char*; no checking: a cast in disguise
10369             char* p = va_arg(ap, char*);
10370             if (p == nullptr) break;
10371             cerr << p << ' ';
10372         }
10374         va_end(ap);             // arg cleanup (don't forget this)
10376         cerr << '\n';
10377         if (severity) exit(severity);
10378     }
10380     void use()
10381     {
10382         error(7, "this", "is", "an", "error", nullptr);
10383         error(7); // crash
10384         error(7, "this", "is", "an", "error");  // crash
10385         const char* is = "is";
10386         string an = "an";
10387         error(7, "this", "is", an, "error"); // crash
10388     }
10390 **Alternative**: Overloading. Templates. Variadic templates.
10392 ##### Note
10394 This is basically the way `printf` is implemented.
10396 ##### Enforcement
10398 * Flag definitions of C-style variadic functions.
10399 * Flag `#include <cstdarg>` and `#include <stdarg.h>`
10401 ## ES.stmt: Statements
10403 Statements control the flow of control (except for function calls and exception throws, which are expressions).
10405 ### <a name="Res-switch-if"></a>ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice
10407 ##### Reason
10409 * Readability.
10410 * Efficiency: A `switch` compares against constants and is usually better optimized than a series of tests in an `if`-`then`-`else` chain.
10411 * A `switch` enables some heuristic consistency checking. For example, have all values of an `enum` been covered? If not, is there a `default`?
10413 ##### Example
10415     void use(int n)
10416     {
10417         switch (n) {   // good
10418         case 0:   // ...
10419         case 7:   // ...
10420         }
10421     }
10423 rather than:
10425     void use2(int n)
10426     {
10427         if (n == 0)   // bad: if-then-else chain comparing against a set of constants
10428             // ...
10429         else if (n == 7)
10430             // ...
10431     }
10433 ##### Enforcement
10435 Flag `if`-`then`-`else` chains that check against constants (only).
10437 ### <a name="Res-for-range"></a>ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice
10439 ##### Reason
10441 Readability. Error prevention. Efficiency.
10443 ##### Example
10445     for (int i = 0; i < v.size(); ++i)   // bad
10446             cout << v[i] << '\n';
10448     for (auto p = v.begin(); p != v.end(); ++p)   // bad
10449         cout << *p << '\n';
10451     for (auto& x : v)    // OK
10452         cout << x << '\n';
10454     for (int i = 1; i < v.size(); ++i) // touches two elements: can't be a range-for
10455         cout << v[i] + v[i - 1] << '\n';
10457     for (int i = 0; i < v.size(); ++i) // possible side-effect: can't be a range-for
10458         cout << f(v, &v[i]) << '\n';
10460     for (int i = 0; i < v.size(); ++i) { // body messes with loop variable: can't be a range-for
10461         if (i % 2 == 0)
10462             continue;   // skip even elements
10463         else
10464             cout << v[i] << '\n';
10465     }
10467 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.
10469 "Messing with the loop variable" in the body of a loop is typically best avoided.
10471 ##### Note
10473 Don't use expensive copies of the loop variable of a range-`for` loop:
10475     for (string s : vs) // ...
10477 This will copy each elements of `vs` into `s`. Better:
10479     for (string& s : vs) // ...
10481 Better still, if the loop variable isn't modified or copied:
10483     for (const string& s : vs) // ...
10485 ##### Enforcement
10487 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.
10489 ### <a name="Res-for-while"></a>ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable
10491 ##### Reason
10493 Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited.
10495 ##### Example
10497     for (int i = 0; i < vec.size(); i++) {
10498         // do work
10499     }
10501 ##### Example, bad
10503     int i = 0;
10504     while (i < vec.size()) {
10505         // do work
10506         i++;
10507     }
10509 ##### Enforcement
10513 ### <a name="Res-while-for"></a>ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable
10515 ##### Reason
10517 Readability.
10519 ##### Example
10521     int events = 0;
10522     for (; wait_for_event(); ++events) {  // bad, confusing
10523         // ...
10524     }
10526 The "event loop" is misleading because the `events` counter has nothing to do with the loop condition (`wait_for_event()`).
10527 Better
10529     int events = 0;
10530     while (wait_for_event()) {      // better
10531         ++events;
10532         // ...
10533     }
10535 ##### Enforcement
10537 Flag actions in `for`-initializers and `for`-increments that do not relate to the `for`-condition.
10539 ### <a name="Res-for-init"></a>ES.74: Prefer to declare a loop variable in the initializer part of a `for`-statement
10541 ##### Reason
10543 Limit the loop variable visibility to the scope of the loop.
10544 Avoid using the loop variable for other purposes after the loop.
10546 ##### Example
10548     for (int i = 0; i < 100; ++i) {   // GOOD: i var is visible only inside the loop
10549         // ...
10550     }
10552 ##### Example, don't
10554     int j;                            // BAD: j is visible outside the loop
10555     for (j = 0; j < 100; ++j) {
10556         // ...
10557     }
10558     // j is still visible here and isn't needed
10560 **See also**: [Don't use a variable for two unrelated purposes](#Res-recycle)
10562 ##### Example
10564     for (string s; cin >> s; ) {
10565         cout << s << '\n';
10566     }
10568 ##### Enforcement
10570 Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop.
10572 **Discussion**: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable
10573 is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.
10575 ### <a name="Res-do"></a>ES.75: Avoid `do`-statements
10577 ##### Reason
10579 Readability, avoidance of errors.
10580 The termination condition is at the end (where it can be overlooked) and the condition is not checked the first time through.
10582 ##### Example
10584     int x;
10585     do {
10586         cin >> x;
10587         // ...
10588     } while (x < 0);
10590 ##### Note
10592 Yes, there are genuine examples where a `do`-statement is a clear statement of a solution, but also many bugs.
10594 ##### Enforcement
10596 Flag `do`-statements.
10598 ### <a name="Res-goto"></a>ES.76: Avoid `goto`
10600 ##### Reason
10602 Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code.
10604 ##### Exception
10606 Breaking out of a nested loop.
10607 In that case, always jump forwards.
10609     for (int i = 0; i < imax; ++i)
10610         for (int j = 0; j < jmax; ++j) {
10611             if (a[i][j] > elem_max) goto finished;
10612             // ...
10613         }
10614     finished:
10615     // ...
10617 ##### Example, bad
10619 There is a fair amount of use of the C goto-exit idiom:
10621     void f()
10622     {
10623         // ...
10624             goto exit;
10625         // ...
10626             goto exit;
10627         // ...
10628     exit:
10629         ... common cleanup code ...
10630     }
10632 This is an ad-hoc simulation of destructors.
10633 Declare your resources with handles with destructors that clean up.
10634 If for some reason you cannot handle all cleanup with destructors for the variables used,
10635 consider `gsl::finally()` as a cleaner and more reliable alternative to `goto exit`
10637 ##### Enforcement
10639 * 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.
10641 ### <a name="Res-continue"></a>ES.77: Minimize the use of `break` and `continue` in loops
10643 ##### Reason
10645  In a non-trivial loop body, it is easy to overlook a `break` or a `continue`.
10647  A `break` in a loop has a dramatically different meaning than a `break` in a `switch`-statement
10648  (and you can have `switch`-statement in a loop and a loop in a `switch`-case).
10650 ##### Example
10652     ???
10654 ##### Alternative
10656 Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
10658     ???
10660 Often. a loop that uses `continue` can equivalently and as clearly be expressed by an `if`-statement.
10662     ???
10664 ##### Note
10666 If you really need to break out a loop, a `break` is typically better than alternatives such as [modifying the loop variable](#Res-loop-counter) or a [`goto`](#Res-goto):
10669 ##### Enforcement
10673 ### <a name="Res-break"></a>ES.78: Always end a non-empty `case` with a `break`
10675 ##### Reason
10677  Accidentally leaving out a `break` is a fairly common bug.
10678  A deliberate fallthrough is a maintenance hazard.
10680 ##### Example
10682     switch (eventType)
10683     {
10684     case Information:
10685         update_status_bar();
10686         break;
10687     case Warning:
10688         write_event_log();
10689     case Error:
10690         display_error_window(); // Bad
10691         break;
10692     }
10694 It is easy to overlook the fallthrough. Be explicit:
10696     switch (eventType)
10697     {
10698     case Information:
10699         update_status_bar();
10700         break;
10701     case Warning:
10702         write_event_log();
10703         // fallthrough
10704     case Error:
10705         display_error_window(); // Bad
10706         break;
10707     }
10709 In C++17, use a `[[fallthrough]]` annotation:
10711     switch (eventType)
10712     {
10713     case Information:
10714         update_status_bar();
10715         break;
10716     case Warning:
10717         write_event_log();
10718         [[fallthrough]];        // C++17
10719     case Error:
10720         display_error_window(); // Bad
10721         break;
10722     }
10724 ##### Note
10726 Multiple case labels of a single statement is OK:
10728     switch (x) {
10729     case 'a':
10730     case 'b':
10731     case 'f':
10732         do_something(x);
10733         break;
10734     }
10736 ##### Enforcement
10738 Flag all fallthroughs from non-empty `case`s.
10740 ### <a name="Res-default"></a>ES.79: Use `default` to handle common cases (only)
10742 ##### Reason
10744  Code clarity.
10745  Improved opportunities for error detection.
10747 ##### Example
10749     enum E { a, b, c , d };
10751     void f1(E x)
10752     {
10753         switch (x) {
10754         case a:
10755             do_something();
10756             break;
10757         case b:
10758             do_something_else();
10759             break;
10760         default:
10761             take_the_default_action();
10762             break;
10763         }
10764     }
10766 Here it is clear that there is a default action and that cases `a` and `b` are special.
10768 ##### Example
10770 But what if there is no default action and you mean to handle only specific cases?
10771 In that case, have an empty default or else it is impossible to know if you meant to handle all cases:
10773     void f2(E x)
10774     {
10775         switch (x) {
10776         case a:
10777             do_something();
10778             break;
10779         case b:
10780             do_something_else();
10781             break;
10782         default:
10783             // do nothing for the rest of the cases
10784             break;
10785         }
10786     }
10788 If you leave out the `default`, a maintainer and/or a compiler may reasonably assume that you intended to handle all cases:
10790     void f2(E x)
10791     {
10792         switch (x) {
10793         case a:
10794             do_something();
10795             break;
10796         case b:
10797         case c:
10798             do_something_else();
10799             break;
10800         }
10801     }
10803 Did you forget case `d` or deliberately leave it out?
10804 Forgetting a case typically happens when a case is added to an enumeration and the person doing so fails to add it to every
10805 switch over the enumerators.
10807 ##### Enforcement
10809 Flag `switch`-statements over an enumeration that don't handle all enumerators and do not have a `default`.
10810 This may yield too many false positives in some code bases; if so, flag only `switch`es that handle most but not all cases
10811 (that was the strategy of the very first C++ compiler).
10813 ### <a name="Res-noname"></a>ES.84: Don't (try to) declare a local variable with no name
10815 ##### Reason
10817 There is no such thing.
10818 What looks to a human like a variable without a name is to the compiler a statement consisting of a temporary that immediately goes out of scope.
10819 To avoid unpleasant surprises.
10821 ###### Example, bad
10823     void f()
10824     {
10825         lock<mutex>{mx};   // Bad
10826         // ...
10827     }
10829 This declares an unnamed `lock` object that immediately goes out of scope at the point of the semicolon.
10830 This is not an uncommon mistake.
10831 In particular, this particular example can lead to hard-to find race conditions.
10832 There are exceedingly clever used of this "idiom", but they are far rarer than the mistakes.
10834 ##### Note
10836     Unnamed function arguments are fine.
10838 ##### Enforcement
10840     Flag statements that are just a temporary
10842 ### <a name="Res-empty"></a>ES.85: Make empty statements visible
10844 ##### Reason
10846 Readability.
10848 ##### Example
10850     for (i = 0; i < max; ++i);   // BAD: the empty statement is easily overlooked
10851     v[i] = f(v[i]);
10853     for (auto x : v) {           // better
10854         // nothing
10855     }
10856     v[i] = f(v[i]);
10858 ##### Enforcement
10860 Flag empty statements that are not blocks and don't contain comments.
10862 ### <a name="Res-loop-counter"></a>ES.86: Avoid modifying loop control variables inside the body of raw for-loops
10864 ##### Reason
10866 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.
10868 ##### Example
10870     for (int i = 0; i < 10; ++i) {
10871         // no updates to i -- ok
10872     }
10874     for (int i = 0; i < 10; ++i) {
10875         //
10876         if (/* something */) ++i; // BAD
10877         //
10878     }
10880     bool skip = false;
10881     for (int i = 0; i < 10; ++i) {
10882         if (skip) { skip = false; continue; }
10883         //
10884         if (/* something */) skip = true;  // Better: using two variable for two concepts.
10885         //
10886     }
10888 ##### Enforcement
10890 Flag variables that are potentially updated (have a non-const use) in both the loop control iteration-expression and the loop body.
10892 ## ES.expr: Expressions
10894 Expressions manipulate values.
10896 ### <a name="Res-complicated"></a>ES.40: Avoid complicated expressions
10898 ##### Reason
10900 Complicated expressions are error-prone.
10902 ##### Example
10904     // bad: assignment hidden in subexpression
10905     while ((c = getc()) != -1)
10907     // bad: two non-local variables assigned in a sub-expressions
10908     while ((cin >> c1, cin >> c2), c1 == c2)
10910     // better, but possibly still too complicated
10911     for (char c1, c2; cin >> c1 >> c2 && c1 == c2;)
10913     // OK: if i and j are not aliased
10914     int x = ++i + ++j;
10916     // OK: if i != j and i != k
10917     v[i] = v[j] + v[k];
10919     // bad: multiple assignments "hidden" in subexpressions
10920     x = a + (b = f()) + (c = g()) * 7;
10922     // bad: relies on commonly misunderstood precedence rules
10923     x = a & b + c * d && e ^ f == 7;
10925     // bad: undefined behavior
10926     x = x++ + x++ + ++x;
10928 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.
10930 ##### Note
10932 C++17 tightens up the rules for the order of evaluation
10933 (left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified; [see ES.43](#Res-order)),
10934 but that doesn't change the fact that complicated expressions are potentially confusing.
10936 ##### Note
10938 A programmer should know and use the basic rules for expressions.
10940 ##### Example
10942     x = k * y + z;             // OK
10944     auto t1 = k * y;           // bad: unnecessarily verbose
10945     x = t1 + z;
10947     if (0 <= x && x < max)   // OK
10949     auto t1 = 0 <= x;        // bad: unnecessarily verbose
10950     auto t2 = x < max;
10951     if (t1 && t2)            // ...
10953 ##### Enforcement
10955 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:
10957 * 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
10958 * writes to aliased variables
10959 * more than N operators (and what should N be?)
10960 * reliance of subtle precedence rules
10961 * uses undefined behavior (can we catch all undefined behavior?)
10962 * implementation defined behavior?
10963 * ???
10965 ### <a name="Res-parens"></a>ES.41: If in doubt about operator precedence, parenthesize
10967 ##### Reason
10969 Avoid errors. Readability. Not everyone has the operator table memorized.
10971 ##### Example
10973     const unsigned int flag = 2;
10974     unsigned int a = flag;
10976     if (a & flag != 0)  // bad: means a&(flag != 0)
10978 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.
10980     if ((a & flag) != 0)  // OK: works as intended
10982 ##### Note
10984 You should know enough not to need parentheses for:
10986     if (a < 0 || a <= max) {
10987         // ...
10988     }
10990 ##### Enforcement
10992 * Flag combinations of bitwise-logical operators and other operators.
10993 * Flag assignment operators not as the leftmost operator.
10994 * ???
10996 ### <a name="Res-ptr"></a>ES.42: Keep use of pointers simple and straightforward
10998 ##### Reason
11000 Complicated pointer manipulation is a major source of errors.
11002 * Do all pointer arithmetic on a `span` (exception ++p in simple loop???)
11003 * Avoid pointers to pointers
11004 * ???
11006 ##### Example
11008     ???
11010 ##### Enforcement
11012 We need a heuristic limiting the complexity of pointer arithmetic statement.
11014 ### <a name="Res-order"></a>ES.43: Avoid expressions with undefined order of evaluation
11016 ##### Reason
11018 You have no idea what such code does. Portability.
11019 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.
11021 ##### Note
11023 C++17 tightens up the rules for the order of evaluation:
11024 left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified.
11026 However, remember that your code may be compiled with a pre-C++17 compiler (e.g., through cut-and-paste) so don't be too clever.
11028 ##### Example
11030     v[i] = ++i;   //  the result is undefined
11032 A good rule of thumb is that you should not read a value twice in an expression where you write to it.
11034 ##### Enforcement
11036 Can be detected by a good analyzer.
11038 ### <a name="Res-order-fct"></a>ES.44: Don't depend on order of evaluation of function arguments
11040 ##### Reason
11042 Because that order is unspecified.
11044 ##### Note
11046 C++17 tightens up the rules for the order of evaluation, but the order of evaluation of function arguments is still unspecified.
11048 ##### Example
11050     int i = 0;
11051     f(++i, ++i);
11053 The call will most likely be `f(0, 1)` or `f(1, 0)`, but you don't know which. Technically, the behavior is undefined.
11055 ##### Example
11057 ??? overloaded operators can lead to order of evaluation problems (shouldn't :-()
11059     f1()->m(f2());   // m(f1(), f2())
11060     cout << f1() << f2();   // operator<<(operator<<(cout, f1()), f2())
11062 ##### Enforcement
11064 Can be detected by a good analyzer.
11066 ### <a name="Res-magic"></a>ES.45: Avoid "magic constants"; use symbolic constants
11068 ##### Reason
11070 Unnamed constants embedded in expressions are easily overlooked and often hard to understand:
11072 ##### Example
11074     for (int m = 1; m <= 12; ++m)   // don't: magic constant 12
11075         cout << month[m] << '\n';
11077 No, we don't all know that there are 12 months, numbered 1..12, in a year. Better:
11079     constexpr int month_count = 12;   // months are numbered 1..12
11081     for (int m = first_month; m <= month_count; ++m)   // better
11082         cout << month[m] << '\n';
11084 Better still, don't expose constants:
11086     for (auto m : month)
11087         cout << m << '\n';
11089 ##### Enforcement
11091 Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list.
11093 ### <a name="Res-narrowing"></a>ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions
11095 ##### Reason
11097 A narrowing conversion destroys information, often unexpectedly so.
11099 ##### Example, bad
11101 A key example is basic narrowing:
11103     double d = 7.9;
11104     int i = d;    // bad: narrowing: i becomes 7
11105     i = (int) d;  // bad: we're going to claim this is still not explicit enough
11107     void f(int x, long y, double d)
11108     {
11109         char c1 = x;   // bad: narrowing
11110         char c2 = y;   // bad: narrowing
11111         char c3 = d;   // bad: narrowing
11112     }
11114 ##### Note
11116 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:
11118     i = narrow_cast<int>(d);   // OK (you asked for it): narrowing: i becomes 7
11119     i = narrow<int>(d);        // OK: throws narrowing_error
11121 We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:
11123     double d = -7.9;
11124     unsigned u = 0;
11126     u = d;                          // BAD
11127     u = narrow_cast<unsigned>(d);   // OK (you asked for it): u becomes 0
11128     u = narrow<unsigned>(d);        // OK: throws narrowing_error
11130 ##### Enforcement
11132 A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:
11134 * flag all floating-point to integer conversions (maybe only `float`->`char` and `double`->`int`. Here be dragons! we need data)
11135 * flag all `long`->`char` (I suspect `int`->`char` is very common. Here be dragons! we need data)
11136 * consider narrowing conversions for function arguments especially suspect
11138 ### <a name="Res-nullptr"></a>ES.47: Use `nullptr` rather than `0` or `NULL`
11140 ##### Reason
11142 Readability. Minimize surprises: `nullptr` cannot be confused with an
11143 `int`. `nullptr` also has a well-specified (very restrictive) type, and thus
11144 works in more scenarios where type deduction might do the wrong thing on `NULL`
11145 or `0`.
11147 ##### Example
11149 Consider:
11151     void f(int);
11152     void f(char*);
11153     f(0);         // call f(int)
11154     f(nullptr);   // call f(char*)
11156 ##### Enforcement
11158 Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation.
11160 ### <a name="Res-casts"></a>ES.48: Avoid casts
11162 ##### Reason
11164 Casts are a well-known source of errors. Make some optimizations unreliable.
11166 ##### Example, bad
11168     double d = 2;
11169     auto p = (long*)&d;
11170     auto q = (long long*)&d;
11171     cout << d << ' ' << *p << ' ' << *q << '\n';
11173 What would you think this fragment prints? The result is at best implementation defined. I got
11175     2 0 4611686018427387904
11177 Adding 
11179     *q = 666;
11180     cout << d << ' ' << *p << ' ' << *q << '\n';
11182 I got 
11184     3.29048e-321 666 666
11186 Surprised? I'm just glad I didn't crash the program.
11188 ##### Note
11190 Programmer who write casts typically assumes that they know what they are doing.
11191 In fact, they often disable the general rules for using values.
11192 Overload resolution and template instantiation usually pick the right function if there is a right function to pick.
11193 If there is not, maybe there ought to be, rather than applying a local fix (cast).
11195 ##### Note
11197 Casts are necessary in a systems programming language.  For example, how else
11198 would we get the address of a device register into a pointer?  However, casts
11199 are seriously overused as well as a major source of errors.
11201 ##### Note
11203 If you feel the need for a lot of casts, there may be a fundamental design problem.
11205 ##### Enforcement
11207 * Force the elimination of C-style casts
11208 * Warn against named casts
11209 * Warn if there are many functional style casts (there is an obvious problem in quantifying 'many').
11211 ### <a name="Res-casts-named"></a>ES.49: If you must use a cast, use a named cast
11213 ##### Reason
11215 Readability. Error avoidance.
11216 Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors.
11218 The named casts are:
11220 * `static_cast`
11221 * `const_cast`
11222 * `reinterpret_cast`
11223 * `dynamic_cast`
11224 * `std::move`         // `move(x)` is an rvalue reference to `x`
11225 * `std::forward`      // `forward(x)` is an rvalue reference to `x`
11226 * `gsl::narrow_cast`  // `narrow_cast<T>(x)` is `static_cast<T>(x)`
11227 * `gsl::narrow`       // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
11229 ##### Example
11231     class B { /* ... */ };
11232     class D { /* ... */ };
11234     template<typename D> D* upcast(B* pb)
11235     {
11236         D* pd0 = pb;                        // error: no implicit conversion from B* to D*
11237         D* pd1 = (D*)pb;                    // legal, but what is done?
11238         D* pd2 = static_cast<D*>(pb);       // error: D is not derived from B
11239         D* pd3 = reinterpret_cast<D*>(pb);  // OK: on your head be it!
11240         D* pd4 = dynamic_cast<D*>(pb);      // OK: return nullptr
11241         // ...
11242     }
11244 The example was synthesized from real-world bugs where `D` used to be derived from `B`, but someone refactored the hierarchy.
11245 The C-style cast is dangerous because it can do any kind of conversion, depriving us of any protection from mistakes (now or in the future).
11247 ##### Note
11249 When converting between types with no information loss (e.g. from `float` to
11250 `double` or `int64` from `int32`), brace initialization may be used instead.
11252     double d {some_float};
11253     int64_t i {some_int32};
11255 This makes it clear that the type conversion was intended and also prevents
11256 conversions between types that might result in loss of precision. (It is a
11257 compilation error to try to initialize a `float` from a `double` in this fashion,
11258 for example.)
11260 ##### Enforcement
11262 Flag C-style and functional casts.
11264 ### <a name="Res-casts-const"></a>ES.50: Don't cast away `const`
11266 ##### Reason
11268 It makes a lie out of `const`.
11270 ##### Note
11272 Usually the reason to "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object.
11273 Examples are caching, memoization, and precomputation.
11274 Such examples are often handled as well or better using `mutable` or an indirection than with a `const_cast`.
11276 ##### Example
11278 Consider keeping previously computed results around for a costly operation:
11280     int compute(int x); // compute a value for x; assume this to be costly
11282     class Cache {   // some type implementing a cache for an int->int operation
11283     public:
11284         pair<bool, int> find(int x) const;   // is there a value for x?
11285         void set(int x, int v);             // make y the value for x
11286         // ...
11287     private:
11288         // ...
11289     };
11291     class X {
11292     public:
11293         int get_val(int x)
11294         {
11295             auto p = cache.find(x);
11296             if (p.first) return p.second;
11297             int val = compute(x);
11298             cache.set(x, val); // insert value for x
11299             return val;
11300         }
11301         // ...
11302     private:
11303         Cache cache;
11304     };
11306 Here, `get_val()` is logically constant, so we would like to make it a `const` member.
11307 To do this we still need to mutate `cache`, so people sometimes resort to a `const_cast`:
11309     class X {   // Suspicious solution based on casting
11310     public:
11311         int get_val(int x) const
11312         {
11313             auto p = cache.find(x);
11314             if (p.first) return p.second;
11315             int val = compute(x);
11316             const_cast<Cache&>(cache).set(x, val);   // ugly
11317             return val;
11318         }
11319         // ...
11320     private:
11321         Cache cache;
11322     };
11324 Fortunately, there is a better solution:
11325 State that `cache` is mutable even for a `const` object:
11327     class X {   // better solution
11328     public:
11329         int get_val(int x) const
11330         {
11331             auto p = cache.find(x);
11332             if (p.first) return p.second;
11333             int val = compute(x);
11334             cache.set(x, val);
11335             return val;
11336         }
11337         // ...
11338     private:
11339         mutable Cache cache;
11340     };
11342 An alternative solution would to store a pointer to the `cache`:
11344     class X {   // OK, but slightly messier solution
11345     public:
11346         int get_val(int x) const
11347         {
11348             auto p = cache->find(x);
11349             if (p.first) return p.second;
11350             int val = compute(x);
11351             cache->set(x, val);
11352             return val;
11353         }
11354         // ...
11355     private:
11356         unique_ptr<Cache> cache;
11357     };
11359 That solution is the most flexible, but requires explicit construction and destruction of `*cache`
11360 (most likely in the constructor and destructor of `X`).
11362 In any variant, we must guard against data races on the `cache` in multithreaded code, possibly using a `std::mutex`.
11364 ##### Enforcement
11366 Flag `const_cast`s. See also [Type.3: Don't use `const_cast` to cast away `const` (i.e., at all)](#Pro-type-constcast) for the related Profile.
11368 ### <a name="Res-range-checking"></a>ES.55: Avoid the need for range checking
11370 ##### Reason
11372 Constructs that cannot overflow do not overflow (and usually run faster):
11374 ##### Example
11376     for (auto& x : v)      // print all elements of v
11377         cout << x << '\n';
11379     auto p = find(v, x);   // find x in v
11381 ##### Enforcement
11383 Look for explicit range checks and heuristically suggest alternatives.
11385 ### <a name="Res-move"></a>ES.56: Write `std::move()` only when you need to explicitly move an object to another scope
11387 ##### Reason
11389 We move, rather than copy, to avoid duplication and for improved performance.
11391 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).
11393 ##### Notes
11395 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.
11397 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`.
11399 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.
11401 ##### Example, bad
11403     void sink(X&& x);   // sink takes ownership of x
11405     void user()
11406     {
11407         X x;
11408         // error: cannot bind an lvalue to a rvalue reference
11409         sink(x);
11410         // OK: sink takes the contents of x, x must now be assumed to be empty
11411         sink(std::move(x));
11413         // ...
11415         // probably a mistake
11416         use(x);
11417     }
11419 Usually, a `std::move()` is used as an argument to a `&&` parameter.
11420 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.
11422     void f() {
11423         string s1 = "supercalifragilisticexpialidocious";
11425         string s2 = s1;             // ok, takes a copy
11426         assert(s1 == "supercalifragilisticexpialidocious");  // ok
11428         // bad, if you want to keep using s1's value
11429         string s3 = move(s1);
11431         // bad, assert will likely fail, s1 likely changed
11432         assert(s1 == "supercalifragilisticexpialidocious");
11433     }
11435 ##### Example
11437     void sink(unique_ptr<widget> p);  // pass ownership of p to sink()
11439     void f() {
11440         auto w = make_unique<widget>();
11441         // ...
11442         sink(std::move(w));               // ok, give to sink()
11443         // ...
11444         sink(w);    // Error: unique_ptr is carefully designed so that you cannot copy it
11445     }
11447 ##### Notes
11449 `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.
11450 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.
11452 Never write `std::move()` just because you've heard "it's more efficient."
11453 In general, don't believe claims of "efficiency" without data (???).
11454 In general, don't complicate your code without reason (??)
11456 ##### Example, bad
11458     vector<int> make_vector() {
11459         vector<int> result;
11460         // ... load result with data
11461         return std::move(result);       // bad; just write "return result;"
11462     }
11464 Never write `return move(local_variable);`, because the language already knows the variable is a move candidate.
11465 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.
11468 ##### Example, bad
11470     vector<int> v = std::move(make_vector());   // bad; the std::move is entirely redundant
11472 Never write `move` on a returned value such as `x = move(f());` where `f` returns by value.
11473 The language already knows that a returned value is a temporary object that can be moved from.
11475 ##### Example
11477     void mover(X&& x) {
11478         call_something(std::move(x));         // ok
11479         call_something(std::forward<X>(x));   // bad, don't std::forward an rvalue reference
11480         call_something(x);                    // suspicious, why not std::move?
11481     }
11483     template<class T>
11484     void forwarder(T&& t) {
11485         call_something(std::move(t));         // bad, don't std::move a forwarding reference
11486         call_something(std::forward<T>(t));   // ok
11487         call_something(t);                    // suspicious, why not std::forward?
11488     }
11490 ##### Enforcement
11492 * 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.
11493 * Flag functions taking an `S&&` parameter if there is no `const S&` overload to take care of lvalues.
11494 * 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.
11495 * Flag when `std::move` is applied to a forwarding reference (`T&&` where `T` is a template parameter type). Use `std::forward` instead.
11496 * 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.)
11497 * Flag when `std::forward` is applied to an rvalue reference (`X&&` where `X` is a concrete type). Use `std::move` instead.
11498 * 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.)
11499 * 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.
11501 ### <a name="Res-new"></a>ES.60: Avoid `new` and `delete` outside resource management functions
11503 ##### Reason
11505 Direct resource management in application code is error-prone and tedious.
11507 ##### Note
11509 also known as "No naked `new`!"
11511 ##### Example, bad
11513     void f(int n)
11514     {
11515         auto p = new X[n];   // n default constructed Xs
11516         // ...
11517         delete[] p;
11518     }
11520 There can be code in the `...` part that causes the `delete` never to happen.
11522 **See also**: [R: Resource management](#S-resource).
11524 ##### Enforcement
11526 Flag naked `new`s and naked `delete`s.
11528 ### <a name="Res-del"></a>ES.61: Delete arrays using `delete[]` and non-arrays using `delete`
11530 ##### Reason
11532 That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.
11534 ##### Example, bad
11536     void f(int n)
11537     {
11538         auto p = new X[n];   // n default constructed Xs
11539         // ...
11540         delete p;   // error: just delete the object p, rather than delete the array p[]
11541     }
11543 ##### Note
11545 This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems.
11547 ##### Enforcement
11549 * if the `new` and the `delete` is in the same scope, mistakes can be flagged.
11550 * if the `new` and the `delete` are in a constructor/destructor pair, mistakes can be flagged.
11552 ### <a name="Res-arr2"></a>ES.62: Don't compare pointers into different arrays
11554 ##### Reason
11556 The result of doing so is undefined.
11558 ##### Example, bad
11560     void f(int n)
11561     {
11562         int a1[7];
11563         int a2[9];
11564         if (&a1[5] < &a2[7]) {}       // bad: undefined
11565         if (0 < &a1[5] - &a2[7]) {}   // bad: undefined
11566     }
11568 ##### Note
11570 This example has many more problems.
11572 ##### Enforcement
11576 ### <a name="Res-slice"></a>ES.63: Don't slice
11578 ##### Reason
11580 Slicing -- that is, copying only part of an object using assignment or initialization -- most often leads to errors because
11581 the object was meant to be considered as a whole.
11582 In the rare cases where the slicing was deliberate the code can be surprising.
11584 ##### Example
11586     class Shape { /* ... */ };
11587     class Circle : public Shape { /* ... */ Point c; int r; };
11589     Circle c {{0, 0}, 42};
11590     Shape s {c};    // copy Shape part of Circle
11592 The result will be meaningless because the center and radius will not be copied from `c` into `s`.
11593 The first defense against this is to [define the base class `Shape` not to allow this](#Rc-copy-virtual).
11595 ##### Alternative
11597 If you mean to slice, define an explicit operation to do so.
11598 This saves readers from confusion.
11599 For example:
11601     class Smiley : public Circle {
11602         public:
11603         Circle copy_circle();
11604         // ...
11605     };
11607     Smiley sm { /* ... */ };
11608     Circle c1 {sm};  // ideally prevented by the definition of Circle
11609     Circle c2 {sm.copy_circle()};
11611 ##### Enforcement
11613 Warn against slicing.
11615 ## <a name="SS-numbers"></a>Arithmetic
11617 ### <a name="Res-mix"></a>ES.100: Don't mix signed and unsigned arithmetic
11619 ##### Reason
11621 Avoid wrong results.
11623 ##### Example
11625     int x = -3;
11626     unsigned int y = 7;
11628     cout << x - y << '\n';  // unsigned result, possibly 4294967286
11629     cout << x + y << '\n';  // unsigned result: 4
11630     cout << x * y << '\n';  // unsigned result, possibly 4294967275
11632 It is harder to spot the problem in more realistic examples.
11634 ##### Note
11636 Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts.
11637 This precludes consistency.
11639 ##### Enforcement
11641 Compilers already know and sometimes warn.
11643 ### <a name="Res-unsigned"></a>ES.101: Use unsigned types for bit manipulation
11645 ##### Reason
11647 Unsigned types support bit manipulation without surprises from sign bits.
11649 ##### Example
11651     unsigned char x = 0b1010'1010;
11652     unsigned char y = ~x;   // y == 0b0101'0101;
11654 ##### Note
11656 Unsigned types can also be useful for modulo arithmetic.
11657 However, if you want modulo arithmetic add
11658 comments as necessary noting the reliance on wraparound behavior, as such code
11659 can be surprising for many programmers.
11661 ##### Enforcement
11663 * Just about impossible in general because of the use of unsigned subscripts in the standard library
11664 * ???
11666 ### <a name="Res-signed"></a>ES.102: Use signed types for arithmetic
11668 ##### Reason
11670 Because most arithmetic is assumed to be signed;
11671 `x-y` yields a negative number when `y>x` except in the rare cases where you really want modulo arithmetic.
11673 ##### Example
11675 Unsigned arithmetic can yield surprising results if you are not expecting it.
11676 This is even more true for mixed signed and unsigned arithmetic.
11678     template<typename T, typename T2>
11679     T subtract(T x, T2 y)
11680     {
11681         return x-y;
11682     }
11684     void test()
11685     {
11686         int s = 5;
11687         unsigned int us = 5;
11688         cout << subtract(s, 7) << '\n';     // -2
11689         cout << subtract(us, 7u) << '\n';   // 4294967294
11690         cout << subtract(s, 7u) << '\n';    // -2
11691         cout << subtract(us, 7) << '\n';    // 4294967294
11692         cout << subtract(s, us+2) << '\n';  // -2
11693         cout << subtract(us, s+2) << '\n';  // 4294967294
11694     }
11696 Here we have been very explicit about what's happening,
11697 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`?
11699 ##### Exception
11701 Use unsigned types if you really want modulo arithmetic - add
11702 comments as necessary noting the reliance on overflow behavior, as such code
11703 is going to be surprising for many programmers.
11705 ##### Example
11707 The standard library uses unsigned types for subscripts.
11708 The build-in array uses signed types for subscripts.
11709 This makes surprises (and bugs) inevitable.
11711     int a[10];
11712     for (int i=0; i < 10; ++i) a[i]=i;
11713     vector<int> v(10);
11714     // compares signed to unsigned; some compilers warn
11715     for (int i=0; v.size() < 10; ++i) v[i]=i;
11717     int a2[-2];         // error: negative size
11719     // OK, but the number of ints (4294967294) is so large that we should get an exception
11720     vector<int> v2(-2);
11722 ##### Enforcement
11724 * Flag mixed signed and unsigned arithmetic
11725 * Flag results of unsigned arithmetic assigned to or printed as signed.
11726 * Flag unsigned literals (e.g. `-2`) used as container subscripts.
11728 ### <a name="Res-overflow"></a>ES.103: Don't overflow
11730 ##### Reason
11732 Overflow usually makes your numeric algorithm meaningless.
11733 Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
11735 ##### Example, bad
11737     int a[10];
11738     a[10] = 7;   // bad
11740     int n = 0;
11741     while (n++ < 10)
11742         a[n - 1] = 9; // bad (twice)
11744 ##### Example, bad
11746     int n = numeric_limits<int>::max();
11747     int m = n + 1;   // bad
11749 ##### Example, bad
11751     int area(int h, int w) { return h * w; }
11753     auto a = area(10'000'000, 100'000'000);   // bad
11755 ##### Exception
11757 Use unsigned types if you really want modulo arithmetic.
11759 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
11761 ##### Enforcement
11765 ### <a name="Res-underflow"></a>ES.104: Don't underflow
11767 ##### Reason
11769 Decrementing a value beyond a minimum value can lead to memory corruption and undefined behavior.
11771 ##### Example, bad
11773     int a[10];
11774     a[-2] = 7;   // bad
11776     int n = 101;
11777     while (n--)
11778         a[n - 1] = 9;   // bad (twice)
11780 ##### Exception
11782 Use unsigned types if you really want modulo arithmetic.
11784 ##### Enforcement
11788 ### <a name="Res-zero"></a>ES.105: Don't divide by zero
11790 ##### Reason
11792 The result is undefined and probably a crash.
11794 ##### Note
11796 This also applies to `%`.
11798 ##### Example; bad
11800     double divide(int a, int b) {
11801         // BAD, should be checked (e.g., in a precondition)
11802         return a / b;
11803     }
11805 ##### Example; good
11807     double divide(int a, int b) {
11808         // good, address via precondition (and replace with contracts once C++ gets them)
11809         Expects(b != 0);
11810         return a / b;
11811     }
11813     double divide(int a, int b) {
11814         // good, address via check
11815         return b ? a / b : quiet_NaN<double>();
11816     }
11818 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
11820 ##### Enforcement
11822 * Flag division by an integral value that could be zero
11824 # <a name="S-performance"></a>Per: Performance
11826 ??? should this section be in the main guide???
11828 This section contains rules for people who need high performance or low-latency.
11829 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.
11830 The rules in this section are more restrictive and intrusive than what is needed for many (most) applications.
11831 Do not blindly try to follow them in general code: achieving the goals of low latency requires extra work.
11833 Performance rule summary:
11835 * [Per.1: Don't optimize without reason](#Rper-reason)
11836 * [Per.2: Don't optimize prematurely](#Rper-Knuth)
11837 * [Per.3: Don't optimize something that's not performance critical](#Rper-critical)
11838 * [Per.4: Don't assume that complicated code is necessarily faster than simple code](#Rper-simple)
11839 * [Per.5: Don't assume that low-level code is necessarily faster than high-level code](#Rper-low)
11840 * [Per.6: Don't make claims about performance without measurements](#Rper-measure)
11841 * [Per.7: Design to enable optimization](#Rper-efficiency)
11842 * [Per.10: Rely on the static type system](#Rper-type)
11843 * [Per.11: Move computation from run time to compile time](#Rper-Comp)
11844 * [Per.12: Eliminate redundant aliases](#Rper-alias)
11845 * [Per.13: Eliminate redundant indirections](#Rper-indirect)
11846 * [Per.14: Minimize the number of allocations and deallocations](#Rper-alloc)
11847 * [Per.15: Do not allocate on a critical branch](#Rper-alloc0)
11848 * [Per.16: Use compact data structures](#Rper-compact)
11849 * [Per.17: Declare the most used member of a time-critical struct first](#Rper-struct)
11850 * [Per.18: Space is time](#Rper-space)
11851 * [Per.19: Access memory predictably](#Rper-access)
11852 * [Per.30: Avoid context switches on the critical path](#Rper-context)
11854 ### <a name="Rper-reason"></a>Per.1: Don't optimize without reason
11856 ##### Reason
11858 If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs.
11860 ##### Note
11862 Some people optimize out of habit or because it's fun.
11866 ### <a name="Rper-Knuth"></a>Per.2: Don't optimize prematurely
11868 ##### Reason
11870 Elaborately optimized code is usually larger and harder to change than unoptimized code.
11874 ### <a name="Rper-critical"></a>Per.3: Don't optimize something that's not performance critical
11876 ##### Reason
11878 Optimizing a non-performance-critical part of a program has no effect on system performance.
11880 ##### Note
11882 If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless.
11884 Put another way: If your program spends 4% of its processing time doing
11885 computation A and 40% of its time doing computation B, a 50% improvement on A is
11886 only as impactful as a 5% improvement on B. (If you don't even know how much
11887 time is spent on A or B, see <a href="#Rper-reason">Per.1</a> and <a
11888 href="#Rper-Knuth">Per.2</a>.)
11890 ### <a name="Rper-simple"></a>Per.4: Don't assume that complicated code is necessarily faster than simple code
11892 ##### Reason
11894 Simple code can be very fast. Optimizers sometimes do marvels with simple code
11896 ##### Example, good
11898     // clear expression of intent, fast execution
11900     vector<uint8_t> v(100000);
11902     for (auto& c : v)
11903         c = ~c;
11905 ##### Example, bad
11907     // intended to be faster, but is actually slower
11909     vector<uint8_t> v(100000);
11911     for (size_t i = 0; i < v.size(); i += sizeof(uint64_t))
11912     {
11913         uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
11914         quad_word = ~quad_word;
11915     }
11917 ##### Note
11923 ### <a name="Rper-low"></a>Per.5: Don't assume that low-level code is necessarily faster than high-level code
11925 ##### Reason
11927 Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code.
11929 ##### Note
11935 ### <a name="Rper-measure"></a>Per.6: Don't make claims about performance without measurements
11937 ##### Reason
11939 The field of performance is littered with myth and bogus folklore.
11940 Modern hardware and optimizers defy naive assumptions; even experts are regularly surprised.
11942 ##### Note
11944 Getting good performance measurements can be hard and require specialized tools.
11946 ##### Note
11948 A few simple microbenchmarks using Unix `time` or the standard library `<chrono>` can help dispel the most obvious myths.
11949 If you can't measure your complete system accurately, at least try to measure a few of your key operations and algorithms.
11950 A profiler can help tell you which parts of your system are performance critical.
11951 Often, you will be surprised.
11955 ### <a name="Rper-efficiency"></a>Per.7: Design to enable optimization
11957 ##### Reason
11959 Because we often need to optimize the initial design.
11960 Because a design that ignore the possibility of later improvement is hard to change.
11962 ##### Example
11964 From the C (and C++) standard:
11966     void qsort (void* base, size_t num, size_t size, int (*compar)(const void*, const void*));
11968 When did you even want to sort memory?
11969 Really, we sort sequences of elements, typically stored in containers.
11970 A call to `qsort` throws away much useful information (e.g., the element type), forces the user to repeat information
11971 already known (e.g., the element size), and forces the user to write extra code (e.g., a function to compare `double`s).
11972 This implies added work for the programmer, is error prone, and deprives the compiler of information needed for optimization.
11974     double data[100];
11975     // ... fill a ...
11977     // 100 chunks of memory of sizeof(double) starting at
11978     // address data using the order defined by compare_doubles
11979     qsort(data, 100, sizeof(double), compare_doubles);
11981 From the point of view of interface design is that `qsort` throws away useful information.
11983 We can do better (in C++98)
11985     template<typename Iter>
11986         void sort(Iter b, Iter e);  // sort [b:e)
11988     sort(data, data + 100);
11990 Here, we use the compiler's knowledge about the size of the array, the type of elements, and how to compare `double`s.
11992 With C++11 plus [concepts](#???), we can do better still
11994     // Sortable specifies that c must be a
11995     // random-access sequence of elements comparable with <
11996     void sort(Sortable& c);
11998     sort(c);
12000 The key is to pass sufficient information for a good implementation to be chosen.
12001 In this, the `sort` interfaces shown here still have a weakness:
12002 They implicitly rely on the element type having less-than (`<`) defined.
12003 To complete the interface, we need a second version that accepts a comparison criteria:
12005     // compare elements of c using p
12006     void sort(Sortable& c, Predicate<Value_type<Sortable>> p);
12008 The standard-library specification of `sort` offers those two versions,
12009 but the semantics is expressed in English rather than code using concepts.
12011 ##### Note
12013 Premature optimization is said to be [the root of all evil](#Rper-Knuth), but that's not a reason to despise performance.
12014 It is never premature to consider what makes a design amenable to improvement, and improved performance is a commonly desired improvement.
12015 Aim to build a set of habits that by default results in efficient, maintainable, and optimizable code.
12016 In particular, when you write a function that is not a one-off implementation detail, consider
12018 * Information passing:
12019 Prefer clean [interfaces](#S-interfaces) carrying sufficient information for later improvement of implementation.
12020 Note that information flows into and out of an implementation through the interfaces we provide.
12021 * Compact data: By default, [use compact data](#Rper-compact), such as `std::vector` and [access it in a systematic fashion](#Rper-access).
12022 If you think you need a linked structure, try to craft the interface so that this structure isn't seen by users.
12023 * Function argument passing and return:
12024 Distinguish between mutable and non-mutable data.
12025 Don't impose a resource management burden on your users.
12026 Don't impose spurious run-time indirections on your users.
12027 Use [conventional ways](#Rf-conventional) of passing information through an interface;
12028 unconventional and/or "optimized" ways of passing data can seriously complicate later reimplementation.
12029 * Abstraction:
12030 Don't overgeneralize; a design that tries to cater for every possible use (and misuse) and defers every design decision for later
12031 (using compile-time or run-time indirections) is usually a complicated, bloated, hard-to-understand mess.
12032 Generalize from concrete examples, preserving performance as we generalize.
12033 Do not generalize based on mere speculation about future needs.
12034 The ideal is zero-overhead generalization.
12035 * Libraries:
12036 Use libraries with good interfaces.
12037 If no library is available build one yourself and imitate the interface style from a good library.
12038 The [standard library](#S-stdlib) is a good first place to look for inspiration.
12039 * Isolation:
12040 Isolate your code from messy and/or old style code by providing an interface of your choosing to it.
12041 This is sometimes called "providing a wrapper" for the useful/necessary but messy code.
12042 Don't let bad designs "bleed into" your code.
12044 ##### Example
12046 Consider:
12048     template <class ForwardIterator, class T>
12049     bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
12051 `binary_search(begin(c), end(c), 7)` will tell you whether `7` is in `c` or not.
12052 However, it will not tell you where that `7` is or whether there are more than one `7`.
12054 Sometimes, just passing the minimal amount of information back (here, `true` or `false`) is sufficient, but a good interface passes
12055 needed information back to the caller. Therefore, the standard library also offers
12057     template <class ForwardIterator, class T>
12058     ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);
12060 `lower_bound` returns an iterator to the first match if any, otherwise `last`.
12062 However, `lower_bound` still doesn't return enough information for all uses, so the standard library also offers
12064     template <class ForwardIterator, class T>
12065     pair<ForwardIterator, ForwardIterator>
12066     equal_range(ForwardIterator first, ForwardIterator last, const T& val);
12068 `equal_range` returns a `pair` of iterators specifying the first and one beyond last match.
12070     auto r = equal_range(begin(c), end(c), 7);
12071     for (auto p = r.first(); p != r.second(), ++p)
12072         cout << *p << '\n';
12074 Obviously, these three interfaces are implemented by the same basic code.
12075 They are simply three ways of presenting the basic binary search algorithm to users,
12076 ranging from the simplest ("make simple things simple!")
12077 to returning complete, but not always needed, information ("don't hide useful information").
12078 Naturally, crafting such a set of interfaces requires experience and domain knowledge.
12080 ##### Note
12082 Do not simply craft the interface to match the first implementation and the first use case you think of.
12083 Once your first initial implementation is complete, review it; once you deploy it, mistakes will be hard to remedy.
12085 ##### Note
12087 A need for efficiency does not imply a need for [low-level code](#Rper-low).
12088 High-level code does not imply slow or bloated.
12090 ##### Note
12092 Things have costs.
12093 Don't be paranoid about costs (modern computers really are very fast),
12094 but have a rough idea of the order of magnitude of cost of what you use.
12095 For example, have a rough idea of the cost of
12096 a memory access,
12097 a function call,
12098 a string comparison,
12099 a system call,
12100 a disk access,
12101 and a message through a network.
12103 ##### Note
12105 If you can only think of one implementation, you probably don't have something for which you can devise a stable interface.
12106 Maybe, it is just an implementation detail - not every piece of code needs a stable interface - but pause and consider.
12107 One question that can be useful is
12108 "what interface would be needed if this operation should be implemented using multiple threads? be vectorized?"
12110 ##### Note
12112 This rule does not contradict the [Don't optimize prematurely](#Rper-Knuth) rule.
12113 It complements it encouraging developers enable later - appropriate and non-premature - optimization, if and where needed.
12115 ##### Enforcement
12117 Tricky.
12118 Maybe looking for `void*` function arguments will find examples of interfaces that hinder later optimization.
12120 ### <a name="Rper-type"></a>Per.10: Rely on the static type system
12122 ##### Reason
12124 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.
12128 ### <a name="Rper-Comp"></a>Per.11: Move computation from run time to compile time
12132 ### <a name="Rper-alias"></a>Per.12: Eliminate redundant aliases
12136 ### <a name="Rper-indirect"></a>Per.13: Eliminate redundant indirections
12140 ### <a name="Rper-alloc"></a>Per.14: Minimize the number of allocations and deallocations
12144 ### <a name="Rper-alloc0"></a>Per.15: Do not allocate on a critical branch
12148 ### <a name="Rper-compact"></a>Per.16: Use compact data structures
12150 ##### Reason
12152 Performance is typically dominated by memory access times.
12156 ### <a name="Rper-struct"></a>Per.17: Declare the most used member of a time-critical struct first
12160 ### <a name="Rper-space"></a>Per.18: Space is time
12162 ##### Reason
12164 Performance is typically dominated by memory access times.
12168 ### <a name="Rper-access"></a>Per.19: Access memory predictably
12170 ##### Reason
12172 Performance is very sensitive to cache performance and cache algorithms favor simple (usually linear) access to adjacent data.
12174 ##### Example
12176     int matrix[rows][cols];
12178     // bad
12179     for (int c = 0; c < cols; ++c)
12180         for (int r = 0; r < rows; ++r)
12181             sum += matrix[r][c];
12183     // good
12184     for (int r = 0; r < rows; ++r)
12185         for (int c = 0; c < cols; ++c)
12186             sum += matrix[r][c];
12188 ### <a name="Rper-context"></a>Per.30: Avoid context switches on the critical path
12192 # <a name="S-concurrency"></a>CP: Concurrency and Parallelism
12194 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).
12195 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)
12196 and so does the basic facilities for expressing concurrency and parallelism.
12197 Here, we articulate a few general principles and rules for using the ISO standard C++ facilities for expressing basic concurrency and parallelism.
12199 The core machine support for concurrent and parallel programming is the thread.
12200 Threads allow you to run multiple instances of your program independently, while sharing
12201 the same memory. Concurrent programming is tricky for many reasons, most
12202 importantly that it is undefined behavior to read data in one thread after it
12203 was written by another thread, if there is no proper synchronization between
12204 those threads. Making existing single-threaded code execute concurrently can be
12205 as trivial as adding `std::async` or `std::thread` strategically, or it can
12206 necessitate a full rewrite, depending on whether the original code was written
12207 in a thread-friendly way.
12209 The concurrency/parallelism rules in this document are designed with three goals
12210 in mind:
12212 * To help you write code that is amenable to being used in a threaded
12213   environment
12214 * To show clean, safe ways to use the threading primitives offered by the
12215   standard library
12216 * To offer guidance on what to do when concurrency and parallelism aren't giving
12217   you the performance gains you need
12219 It is also important to note that concurrency in C++ is an unfinished
12220 story. C++11 introduced many core concurrency primitives, C++14 improved on
12221 them, and it seems that there is much interest in making the writing of
12222 concurrent programs in C++ even easier. We expect some of the library-related
12223 guidance here to change significantly over time.
12225 This section needs a lot of work (obviously).
12226 Please note that we start with rules for relative non-experts.
12227 Real experts must wait a bit;
12228 contributions are welcome,
12229 but please think about the majority of programmers who are struggling to get their concurrent programs correct and performant.
12231 Concurrency and parallelism rule summary:
12233 * [CP.1: Assume that your code will run as part of a multi-threaded program](#Rconc-multi)
12234 * [CP.2: Avoid data races](#Rconc-races)
12235 * [CP.3: Minimize explicit sharing of writable data](#Rconc-data)
12236 * [CP.4: Think in terms of tasks, rather than threads](#Rconc-task)
12237 * [CP.8: Don't try to use `volatile` for synchronization](#Rconc-volatile)
12238 * [CP.9: Whenever feasible use tools to validate your concurrent code](#Rconc-tools)
12240 See also:
12242 * [CP.con: Concurrency](#SScp-con)
12243 * [CP.par: Parallelism](#SScp-par)
12244 * [CP.mess: Message passing](#SScp-mess)
12245 * [CP.vec: Vectorization](#SScp-vec)
12246 * [CP.free: Lock-free programming](#SScp-free)
12247 * [CP.etc: Etc. concurrency rules](#SScp-etc)
12249 ### <a name="Rconc-multi"></a>CP.1: Assume that your code will run as part of a multi-threaded program
12251 ##### Reason
12253 It is hard to be certain that concurrency isn't used now or will be sometime in the future.
12254 Code gets re-used.
12255 Libraries using threads may be used from some other part of the program.
12256 Note that this applies most urgently to library code and least urgently to stand-alone applications.
12257 However, thanks to the magic of cut-and-paste, code fragments can turn up in unexpected places.
12259 ##### Example
12261     double cached_computation(double x)
12262     {
12263         static double cached_x = 0.0;
12264         static double cached_result = COMPUTATION_OF_ZERO;
12265         double result;
12267         if (cached_x == x)
12268             return cached_result;
12269         result = computation(x);
12270         cached_x = x;
12271         cached_result = result;
12272         return result;
12273     }
12275 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.
12277 There are several ways that this example could be made safe for a multi-threaded environment:
12279 * Delegate concurrency concerns upwards to the caller.
12280 * Mark the `static` variables as `thread_local` (which might make caching less effective).
12281 * Implement concurrency control, for example, protecting the two `static` variables with a `static` lock (which might reduce performance).
12282 * Have the caller provide the memory to be used for the cache, thereby delegating both memory allocation and concurrency concerns upwards to the caller.
12283 * Refuse to build and/or run in a multi-threaded environment.
12284 * Provide two implementations, one which is used in single-threaded environments and another which is used in multi-threaded environments.
12286 ##### Exception
12288 Code that is never run in a multi-threaded environment.
12290 Be careful: there are many examples where code that was "known" to never run in a multi-threaded program
12291 was run as part of a multi-threaded program. Often years later.
12292 Typically, such programs lead to a painful effort to remove data races.
12293 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.
12295 ### <a name="Rconc-races"></a>CP.2: Avoid data races
12297 ##### Reason
12299 Unless you do, nothing is guaranteed to work and subtle errors will persist.
12301 ##### Note
12303 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.
12304 For further information of how to use synchronization well to eliminate data races, please consult a good book about concurrency.
12306 ##### Example, bad
12308 There are many examples of data races that exist, some of which are running in
12309 production software at this very moment. One very simple example:
12311     int get_id() {
12312       static int id = 1;
12313       return id++;
12314     }
12316 The increment here is an example of a data race. This can go wrong in many ways,
12317 including:
12319 * Thread A loads the value of `id`, the OS context switches A out for some
12320   period, during which other threads create hundreds of IDs. Thread A is then
12321   allowed to run again, and `id` is written back to that location as A's read of
12322   `id` plus one.
12323 * Thread A and B load `id` and increment it simultaneously.  They both get the
12324   same ID.
12326 Local static variables are a common source of data races.
12328 ##### Example, bad:
12330     void f(fstream&  fs, regex pat)
12331     {
12332         array<double, max> buf;
12333         int sz = read_vec(fs, buf, max);            // read from fs into buf
12334         gsl::span<double> s {buf};
12335         // ...
12336         auto h1 = async([&]{ sort(par, s); });     // spawn a task to sort
12337         // ...
12338         auto h2 = async([&]{ return find_all(buf, sz, pat); });   // span a task to find matches
12339         // ...
12340     }
12342 Here, we have a (nasty) data race on the elements of `buf` (`sort` will both read and write).
12343 All data races are nasty.
12344 Here, we managed to get a data race on data on the stack.
12345 Not all data races are as easy to spot as this one.
12347 ##### Example, bad:
12349     // code not controlled by a lock
12351     unsigned val;
12353     if (val < 5) {
12354         // ... other thread can change val here ...
12355         switch (val) {
12356         case 0: // ...
12357         case 1: // ...
12358         case 2: // ...
12359         case 3: // ...
12360         case 4: // ...
12361         }
12362     }
12364 Now, a compiler that does not know that `val` can change will  most likely implement that `switch` using a jump table with five entries.
12365 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.
12366 Really, "all bets are off" if you get a data race.
12367 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;
12368 this can be a security risk.
12370 ##### Enforcement
12372 Some is possible, do at least something.
12373 There are commercial and open-source tools that try to address this problem,
12374 but be aware that solutions have costs and blind spots.
12375 Static tools often have many false positives and run-time tools often have a significant cost.
12376 We hope for better tools.
12377 Using multiple tools can catch more problems than a single one.
12379 There are other ways you can mitigate the chance of data races:
12381 * Avoid global data
12382 * Avoid `static` variables
12383 * More use of value types on the stack (and don't pass pointers around too much)
12384 * More use of immutable data (literals, `constexpr`, and `const`)
12386 ### <a name="Rconc-data"></a>CP.3: Minimize explicit sharing of writable data
12388 ##### Reason
12390 If you don't share writable data, you can't have a data race.
12391 The less sharing you do, the less chance you have to forget to synchronize access (and get data races).
12392 The less sharing you do, the less chance you have to wait on a lock (so performance can improve).
12394 ##### Example
12396     bool validate(const vector<Reading>&);
12397     Graph<Temp_node> temperature_gradiants(const vector<Reading>&);
12398     Image altitude_map(const vector<Reading>&);
12399     // ...
12401     void process_readings(istream& socket1)
12402     {
12403         vector<Reading> surface_readings;
12404         socket1 >> surface_readings;
12405         if (!socket1) throw Bad_input{};
12407         auto h1 = async([&] { if (!validate(surface_readings) throw Invalide_data{}; });
12408         auto h2 = async([&] { return temperature_gradiants(surface_readings); });
12409         auto h3 = async([&] { return altitude_map(surface_readings); });
12410         // ...
12411         auto v1 = h1.get();
12412         auto v2 = h2.get();
12413         auto v3 = h3.get();
12414         // ...
12415     }
12417 Without those `const`s, we would have to review every asynchronously invoked function for potential data races on `surface_readings`.
12419 ##### Note
12421 Immutable data can be safely and efficiently shared.
12422 No locking is needed: You can't have a data race on a constant.
12424 ##### Enforcement
12429 ### <a name="Rconc-task"></a>CP.4: Think in terms of tasks, rather than threads
12431 ##### Reason
12433 A `thread` is an implementation concept, a way of thinking about the machine.
12434 A task is an application notion, something you'd like to do, preferably concurrently with other tasks.
12435 Application concepts are easier to reason about.
12437 ##### Example
12439     ???
12441 ##### Note
12443 With the exception of `async()`, the standard-library facilities are low-level, machine-oriented, threads-and-lock level.
12444 This is a necessary foundation, but we have to try to raise the level of abstraction: for productivity, for reliability, and for performance.
12445 This is a potent argument for using higher level, more applications-oriented libraries (if possibly, built on top of standard-library facilities).
12447 ##### Enforcement
12451 ### <a name="Rconc-volatile"></a>CP.8: Don't try to use `volatile` for synchronization
12453 ##### Reason
12455 In C++, unlike some other languages, `volatile` does not provide atomicity, does not synchronize between threads,
12456 and does not prevent instruction reordering (neither compiler nor hardware).
12457 It simply has nothing to do with concurrency.
12459 ##### Example, bad:
12461     int free_slots = max_slots; // current source of memory for objects
12463     Pool* use()
12464     {
12465         if (int n = free_slots--) return &pool[n];
12466     }
12468 Here we have a problem:
12469 This is perfectly good code in a single-threaded program, but have two treads execute this and
12470 there is a race condition on `free_slots` so that two threads might get the same value and `free_slots`.
12471 That's (obviously) a bad data race, so people trained in other languages may try to fix it like this:
12473     volatile int free_slots = max_slots; // current source of memory for objects
12475     Pool* use()
12476     {
12477         if (int n = free_slots--) return &pool[n];
12478     }
12480 This has no effect on synchronization: The data race is still there!
12482 The C++ mechanism for this is `atomic` types:
12484     atomic<int> free_slots = max_slots; // current source of memory for objects
12486     Pool* use()
12487     {
12488         if (int n = free_slots--) return &pool[n];
12489     }
12491 Now the `--` operation is atomic,
12492 rather than a read-increment-write sequence where another thread might get in-between the individual operations.
12494 ##### Alternative
12496 Use `atomic` types where you might have used `volatile` in some other language.
12497 Use a `mutex` for more complicated examples.
12499 ##### See also
12501 [(rare) proper uses of `volatile`](#Rconc-volatile2)
12503 ### <a name="Rconc-tools"></a>CP.9: Whenever feasible use tools to validate your concurrent code
12505 Experience shows that concurrent code is exceptionally hard to get right
12506 and that compile-time checking, run-time checks, and testing are less effective at finding concurrency errors
12507 than they are at finding errors in sequential code.
12508 Subtle concurrency errors can have dramatically bad effects, including memory corruption and deadlocks.
12510 ##### Example
12512     ???
12514 ##### Note
12516 Thread safety is challenging, often getting the better of experienced programmers: tooling is an important strategy to mitigate those risks.
12517 There are many tools "out there", both commercial and open-source tools, both research and production tools.
12518 Unfortunately people's needs and constraints differ so dramatically that we cannot make specific recommendations,
12519 but we can mention:
12521 * Static enforcement tools: both [clang](http://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
12522 and some older versions of [GCC](https://gcc.gnu.org/wiki/ThreadSafetyAnnotation)
12523 have some support for static annotation of thread safety properties.
12524 Consistent use of this technique turns many classes of thread-safety errors into compile-time errors.
12525 The annotations are generally local (marking a particular member variable as guarded by a particular mutex),
12526 and are usually easy to learn. However, as with many static tools, it can often present false negatives;
12527 cases that should have been caught but were allowed.
12529 * dynamic enforcement tools: Clang's [Thread Sanitizer](http://clang.llvm.org/docs/ThreadSanitizer.html) (aka TSAN)
12530 is a powerful example of dynamic tools: it changes the build and execution of your program to add bookkeeping on memory access,
12531 absolutely identifying data races in a given execution of your binary.
12532 The cost for this is both memory (5-10x in most cases) and CPU slowdown (2-20x).
12533 Dynamic tools like this are best when applied to integration tests, canary pushes, or unittests that operate on multiple threads.
12534 Workload matters: When TSAN identifies a problem, it is effectively always an actual data race,
12535 but it can only identify races seen in a given execution.
12537 ##### Enforcement
12539 It is up to an application builder to choose which support tools are valuable for a particular applications.
12541 ## <a name="SScp-con"></a>CP.con: Concurrency
12543 This section focuses on relatively ad-hoc uses of multiple threads communicating through shared data.
12545 * For parallel algorithms, see [parallelism](#SScp-par)
12546 * For inter-task communication without explicit sharing, see [messaging](#SScp-mess)
12547 * For vector parallel code, see [vectorization](#SScp-vec)
12548 * For lock-free programming, see [lock free](#SScp-free)
12550 Concurrency rule summary:
12552 * [CP.20: Use RAII, never plain `lock()`/`unlock()`](#Rconc-raii)
12553 * [CP.21: Use `std::lock()` or `std::scoped_lock` to acquire multiple `mutex`es](#Rconc-lock)
12554 * [CP.22: Never call unknown code while holding a lock (e.g., a callback)](#Rconc-unknown)
12555 * [CP.23: Think of a joining `thread` as a scoped container](#Rconc-join)
12556 * [CP.24: Think of a detached `thread` as a global container](#Rconc-detach)
12557 * [CP.25: Prefer `gsl::raii_thread` over `std::thread` unless you plan to `detach()`](#Rconc-raii_thread)
12558 * [CP.26: Prefer `gsl::detached_thread` over `std::thread` if you plan to `detach()`](#Rconc-detached_thread)
12559 * [CP.27: Use plain `std::thread` for `thread`s that detach based on a run-time condition (only)](#Rconc-thread)
12560 * [CP.28: Remember to join scoped `thread`s that are not `detach()`ed](#Rconc-join-undetached)
12561 * [CP.30: Do not pass pointers to local variables to non-`raii_thread`s](#Rconc-pass)
12562 * [CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer](#Rconc-data-by-value)
12563 * [CP.32: To share ownership between unrelated `thread`s use `shared_ptr`](#Rconc-shared)
12564 * [CP.40: Minimize context switching](#Rconc-switch)
12565 * [CP.41: Minimize thread creation and destruction](#Rconc-create)
12566 * [CP.42: Don't `wait` without a condition](#Rconc-wait)
12567 * [CP.43: Minimize time spent in a critical section](#Rconc-time)
12568 * [CP.44: Remember to name your `lock_guard`s and `unique_lock`s](#Rconc-name)
12569 * [CP.50: Define a `mutex` together with the data it protects](#Rconc-mutex)
12570 * ??? when to use a spinlock
12571 * ??? when to use `try_lock()`
12572 * ??? when to prefer `lock_guard` over `unique_lock`
12573 * ??? Time multiplexing
12574 * ??? when/how to use `new thread`
12576 ### <a name="Rconc-raii"></a>CP.20: Use RAII, never plain `lock()`/`unlock()`
12578 ##### Reason
12580 Avoids nasty errors from unreleased locks.
12582 ##### Example, bad
12584     mutex mtx;
12586     void do_stuff()
12587     {
12588         mtx.lock();
12589         // ... do stuff ...
12590         mtx.unlock();
12591     }
12593 Sooner or later, someone will forget the `mtx.unlock()`, place a `return` in the `... do stuff ...`, throw an exception, or something.
12595     mutex mtx;
12597     void do_stuff()
12598     {
12599         unique_lock<mutex> lck {mtx};
12600         // ... do stuff ...
12601     }
12603 ##### Enforcement
12605 Flag calls of member `lock()` and `unlock()`.  ???
12608 ### <a name="Rconc-lock"></a>CP.21: Use `std::lock()` or `std::scoped_lock` to acquire multiple `mutex`es
12610 ##### Reason
12612 To avoid deadlocks on multiple `mutex`es.
12614 ##### Example
12616 This is asking for deadlock:
12618     // thread 1
12619     lock_guard<mutex> lck1(m1);
12620     lock_guard<mutex> lck2(m2);
12622     // thread 2
12623     lock_guard<mutex> lck2(m2);
12624     lock_guard<mutex> lck1(m1);
12626 Instead, use `lock()`:
12628     // thread 1
12629     lock(lck1, lck2);
12630     lock_guard<mutex> lck1(m1, adopt_lock);
12631     lock_guard<mutex> lck2(m2, adopt_lock);
12633     // thread 2
12634     lock(lck2, lck1);
12635     lock_guard<mutex> lck2(m2, adopt_lock);
12636     lock_guard<mutex> lck1(m1, adopt_lock);
12638 or (better, but C++17 only):
12640     // thread 1
12641     scoped_lock<mutex, mutex> lck1(m1, m2);
12643     // thread 2
12644     scoped_lock<mutex, mutex> lck2(m2, m1);
12646 Here, the writers of `thread1` and `thread2` are still not agreeing on the order of the `mutex`es, but order no longer matters.
12648 ##### Note
12650 In real code, `mutex`es are rarely named to conveniently remind the programmer of an intended relation and intended order of acquisition.
12651 In real code, `mutex`es are not always conveniently acquired on consecutive lines.
12653 In C++17 it's possible to write plain
12655     lock_guard lck1(m1, adopt_lock);
12657 and have the `mutex` type deduced.
12659 ##### Enforcement
12661 Detect the acquisition of multiple `mutex`es.
12662 This is undecidable in general, but catching common simple examples (like the one above) is easy.
12665 ### <a name="Rconc-unknown"></a>CP.22: Never call unknown code while holding a lock (e.g., a callback)
12667 ##### Reason
12669 If you don't know what a piece of code does, you are risking deadlock.
12671 ##### Example
12673     void do_this(Foo* p)
12674     {
12675         lock_guard<mutex> lck {my_mutex};
12676         // ... do something ...
12677         p->act(my_data);
12678         // ...
12679     }
12681 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),
12682 it may call `do_this` (recursively) and cause a deadlock on `my_mutex`.
12683 Maybe it will lock on a different mutex and not return in a reasonable time, causing delays to any code calling `do_this`.
12685 ##### Example
12687 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.
12688 Such problem can often be solved by using a `recursive_mutex`. For example:
12690     recursive_mutex my_mutex;
12692     template<typename Action>
12693     void do_something(Action f)
12694     {
12695         unique_lock<recursive_mutex> lck {my_mutex};
12696         // ... do something ...
12697         f(this);    // f will do something to *this
12698         // ...
12699     }
12701 If, as it is likely, `f()` invokes operations on `*this`, we must make sure that the object's invariant holds before the call.
12703 ##### Enforcement
12705 * Flag calling a virtual function with a non-recursive `mutex` held
12706 * Flag calling a callback with a non-recursive `mutex` held
12709 ### <a name="Rconc-join"></a>CP.23: Think of a joining `thread` as a scoped container
12711 ##### Reason
12713 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
12714 If a `thread` joins, we can safely pass pointers to objects in the scope of the `thread` and its enclosing scopes.
12716 ##### Example
12718     void f(int * p)
12719     {
12720         // ...
12721         *p = 99;
12722         // ...
12723     }
12724     int glob = 33;
12726     void some_fct(int* p)
12727     {
12728         int x = 77;
12729         raii_thread t0(f, &x);           // OK
12730         raii_thread t1(f, p);            // OK
12731         raii_thread t2(f, &glob);        // OK
12732         auto q = make_unique<int>(99);
12733         raii_thread t3(f, q.get());      // OK
12734         // ...
12735     }
12737 An `raii_thread` is a `std::thread` with a destructor that joined and cannot be `detached()`.
12738 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointer to it.
12739 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
12740 these `thread`s can be seen as just a function object called from `some_fct`.
12742 ##### Enforcement
12744 Ensure that `raii_thread`s don't `detach()`.
12745 After that, the usual lifetime and ownership (for local objects) enforcement applies.
12748 ### <a name="Rconc-detach"></a>CP.24: Think of a detached `thread` as a global container
12750 ##### Reason
12752 To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a `thread`.
12753 If a `thread` is detached, we can safely pass pointers to static and free store objects (only).
12755 ##### Example
12757     void f(int * p)
12758     {
12759         // ...
12760         *p = 99;
12761         // ...
12762     }
12764     int glob = 33;
12766     void some_fct(int* p)
12767     {
12768         int x = 77;
12769         std::thread t0(f, &x);           // bad
12770         std::thread t1(f, p);            // bad
12771         std::thread t2(f, &glob);        // OK
12772         auto q = make_unique<int>(99);
12773         std::thread t3(f, q.get());      // bad
12774         // ...
12775         t0.detach();
12776         t1.detach();
12777         t2.detach();
12778         t3.detach();
12779         // ...
12780     }
12782 By "OK" we mean that the object will be in scope ("live") for as long as a `thread` can use the pointers to it.
12783 By "bad" we mean that a `thread` may use a pointer after the pointed-to object is destroyed.
12784 The fact that `thread`s run concurrently doesn't affect the lifetime or ownership issues here;
12785 these `thread`s can be seen as just a function object called from `some_fct`.
12787 ##### Note
12789 Even objects with static storage duration can be problematic if used from detached threads: if the
12790 thread continues until the end of the program, it might be running concurrently with the destruction
12791 of objects with static storage duration, and thus accesses to such objects might race.
12793 ##### Enforcement
12795 In general, it is undecidable whether a `detach()` is executed for a `thread`, but simple common cases are easily detected.
12796 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;
12797 After that, the usual lifetime and ownership (for global objects) enforcement applies.
12800 ### <a name="Rconc-raii_thread"></a>CP.25: Prefer `gsl::raii_thread` over `std::thread` unless you plan to `detach()`
12802 ##### Reason
12804 An `raii_thread` is a thread that joins at the end of its scope.
12806 Detached threads are hard to monitor.
12808 ??? Place all "immortal threads" on the free store rather than `detach()`?
12810 ##### Example
12812     ???
12814 ##### Enforcement
12818 ### <a name="Rconc-detached_thread"></a>CP.26: Prefer `gsl::detached_thread` over `std::thread` if you plan to `detach()`
12820 ##### Reason
12822 Often, the need to `detach` is inherent in the `thread`s task.
12823 Documenting that aids comprehension and helps static analysis.
12825 ##### Example
12827     void heartbeat();
12829     void use()
12830     {
12831         gsl::detached_thread t1(heartbeat);    // obviously need not be joined
12832         std::thread t2(heartbeat);             // do we need to join? (read the code for heartbeat())
12833         // ...
12834     }
12836 Flag unconditional `detach` on a plain `thread`
12839 ### <a name="Rconc-thread"></a>CP.27: Use plain `std::thread` for `thread`s that detach based on a run-time condition (only)
12841 ##### Reason
12843 `thread`s that are supposed to unconditionally `join` or unconditionally `detach` can be clearly identified as such.
12844 The plain `thread`s should be assumed to use the full generality of `std::thread`.
12846 ##### Example
12848     void tricky(thread* t, int n)
12849     {
12850         // ...
12851         if (is_odd(n))
12852             t->detach();
12853         // ...
12854     }
12856     void use(int n)
12857     {
12858         thread t { tricky, this, n };
12859         // ...
12860         // ... should I join here? ...
12861     }
12863 ##### Enforcement
12869 ### <a name="Rconc-join-undetached"></a>CP.28: Remember to join scoped `thread`s that are not `detach()`ed
12871 ##### Reason
12873 A `thread` that has not been `detach()`ed when it is destroyed terminates the program.
12875 ##### Example, bad
12877     void f() { std::cout << "Hello "; }
12879     struct F {
12880         void operator()() { std::cout << "parallel world "; }
12881     };
12883     int main()
12884     {
12885         std::thread t1{f};      // f() executes in separate thread
12886         std::thread t2{F()};    // F()() executes in separate thread
12887     }  // spot the bugs
12889 ##### Example
12891     void f() { std::cout << "Hello "; }
12893     struct F {
12894         void operator()() { std::cout << "parallel world "; }
12895     };
12897     int main()
12898     {
12899         std::thread t1{f};      // f() executes in separate thread
12900         std::thread t2{F()};    // F()() executes in separate thread
12902         t1.join();
12903         t2.join();
12904     }  // one bad bug left
12906 ??? Is `cout` synchronized?
12908 ##### Enforcement
12910 * Flag `join`s for `raii_thread`s ???
12911 * Flag `detach`s for `detached_thread`s
12914 ### <a name="RRconc-pass"></a>CP.30: Do not pass pointers to local variables to non-`raii_thread`s
12916 ##### Reason
12918 In general, you cannot know whether a non-`raii_thread` will outlive the scope of the variables, so that those pointers will become invalid.
12920 ##### Example, bad
12922     void use()
12923     {
12924         int x = 7;
12925         thread t0 { f, ref(x) };
12926         // ...
12927         t0.detach();
12928     }
12930 The `detach` may not be so easy to spot.
12931 Use a `raii_thread` or don't pass the pointer.
12933 ##### Example, bad
12935     ??? put pointer to a local on a queue that is read by a longer-lived thread ???
12937 ##### Enforcement
12939 Flag pointers to locals passed in the constructor of a plain `thread`.
12942 ### <a name="Rconc-data-by-value"></a>CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer
12944 ##### Reason
12946 Copying a small amount of data is cheaper to copy and access than to share it using some locking mechanism.
12947 Copying naturally gives unique ownership (simplifies code) and eliminates the possibility of data races.
12949 ##### Note
12951 Defining "small amount" precisely is impossible.
12953 ##### Example
12955     string modify1(string);
12956     void modify2(shared_ptr<string>);
12958     void fct(string& s)
12959     {
12960         auto res = async(modify1, s);
12961         async(modify2, &s);
12962     }
12964 The call of `modify1` involves copying two `string` values; the call of `modify2` does not.
12965 On the other hand, the implementation of `modify1` is exactly as we would have written it for single-threaded code,
12966 whereas the implementation of `modify2` will need some form of locking to avoid data races.
12967 If the string is short (say 10 characters), the call of `modify1` can be surprisingly fast;
12968 essentially all the cost is in the `thread` switch. If the string is long (say 1,000,000 characters), copying it twice
12969 is probably not a good idea.
12971 Note that this argument has nothing to do with `sync` as such. It applies equally to considerations about whether to use
12972 message passing or shared memory.
12974 ##### Enforcement
12979 ### <a name="Rconc-shared"></a>[CP.32: To share ownership between unrelated `thread`s use `shared_ptr`
12981 ##### Reason
12983 If threads are unrelated (that is, not known to be in the same scope or one within the lifetime of the other)
12984 and they need to share free store memory that needs to be deleted, a `shared_ptr` (or equivalent) is the only
12985 safe way to ensure proper deletion.
12987 ##### Example
12989     ???
12991 ##### Note
12993 * 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.
12994 * An object on free store that is never to be deleted can be shared.
12995 * An object owned by one thread can be safely shared with another as long as that second thread doesn't outlive the owner.
12997 ##### Enforcement
13002 ### <a name="Rconc-switch"></a>CP.40: Minimize context switching
13004 ##### Reason
13006 Context switches are expensive.
13008 ##### Example
13010     ???
13012 ##### Enforcement
13017 ### <a name="Rconc-create"></a>CP.41: Minimize thread creation and destruction
13019 ##### Reason
13021 Thread creation is expensive.
13023 ##### Example
13025     void worker(Message m)
13026     {
13027         // process
13028     }
13030     void master(istream& is)
13031     {
13032         for (Message m; is >> m; )
13033             run_list.push_back(new thread(worker, m));
13034     }
13036 This spawns a `thread` per message, and the `run_list` is presumably managed to destroy those tasks once they are finished.
13038 Instead, we could have a set of pre-created worker threads processing the messages
13040     Sync_queue<Message> work;
13042     void master(istream& is)
13043     {
13044         for (Message m; is >> m; )
13045             work.put(m);
13046     }
13048     void worker()
13049     {
13050         for (Message m; m = work.get(); ) {
13051             // process
13052         }
13053     }
13055     void workers()  // set up worker threads (specifically 4 worker threads)
13056     {
13057         raii_thread w1 {worker};
13058         raii_thread w2 {worker};
13059         raii_thread w3 {worker};
13060         raii_thread w4 {worker};
13061     }
13063 ##### Note
13065 If your system has a good thread pool, use it.
13066 If your system has a good message queue, use it.
13068 ##### Enforcement
13073 ### <a name="Rconc-wait"></a>CP.42: Don't `wait` without a condition
13075 ##### Reason
13077 A `wait` without a condition can miss a wakeup or wake up simply to find that there is no work to do.
13079 ##### Example, bad
13081     std::condition_variable cv;
13082     std::mutex mx;
13084     void thread1()
13085     {
13086         while (true) {
13087             // do some work ...
13088             std::unique_lock<std::mutex> lock(mx);
13089             cv.notify_one();    // wake other thread
13090         }
13091     }
13093     void thread2()
13094     {
13095         while (true) {
13096             std::unique_lock<std::mutex> lock(mx);
13097             cv.wait(lock);    // might block forever
13098             // do work ...
13099         }
13100     }
13102 Here, if some other `thread` consumes `thread1`'s notification, `thread2` can wait forever.
13104 ##### Example
13106     template<typename T>
13107     class Sync_queue {
13108     public:
13109         void put(const T& val);
13110         void put(T&& val);
13111         void get(T& val);
13112     private:
13113         mutex mtx;
13114         condition_variable cond;    // this controls access
13115         list<T> q;
13116     };
13118     template<typename T>
13119     void Sync_queue<T>::put(const T& val)
13120     {
13121         lock_guard<mutex> lck(mtx);
13122         q.push_back(val);
13123         cond.notify_one();
13124     }
13126     template<typename T>
13127     void Sync_queue<T>::get(T& val)
13128     {
13129         unique_lock<mutex> lck(mtx);
13130         cond.wait(lck, [this]{ return !q.empty(); });    // prevent spurious wakeup
13131         val = q.front();
13132         q.pop_front();
13133     }
13135 Now if the queue is empty when a thread executing `get()` wakes up (e.g., because another thread has gotten to `get()` before it),
13136 it will immediately go back to sleep, waiting.
13138 ##### Enforcement
13140 Flag all `wait`s without conditions.
13143 ### <a name="Rconc-time"></a>CP.43: Minimize time spent in a critical section
13145 ##### Reason
13147 The less time is spent with a `mutex` taken, the less chance that another `thread` has to wait,
13148 and `thread` suspension and resumption are expensive.
13150 ##### Example
13152     void do_something() // bad
13153     {
13154         unique_lock<mutex> lck(my_lock);
13155         do0();  // preparation: does not need lock
13156         do1();  // transaction: needs locking
13157         do2();  // cleanup: does not need locking
13158     }
13160 Here, we are holding the lock for longer than necessary:
13161 We should not have taken the lock before we needed it and should have released it again before starting the cleanup.
13162 We could rewrite this to
13164     void do_something() // bad
13165     {
13166         do0();  // preparation: does not need lock
13167         my_lock.lock();
13168         do1();  // transaction: needs locking
13169         my_lock.unlock();
13170         do2();  // cleanup: does not need locking
13171     }
13173 But that compromises safety and violates the [use RAII](#Rconc-raii) rule.
13174 Instead, add a block for the critical section:
13176     void do_something() // OK
13177     {
13178         do0();  // preparation: does not need lock
13179         {
13180             unique_lock<mutex> lck(my_lock);
13181             do1();  // transaction: needs locking
13182         }
13183         do2();  // cleanup: does not need locking
13184     }
13186 ##### Enforcement
13188 Impossible in general.
13189 Flag "naked" `lock()` and `unlock()`.
13192 ### <a name="Rconc-name"></a>CP.44: Remember to name your `lock_guard`s and `unique_lock`s
13194 ##### Reason
13196 An unnamed local objects is a temporary that immediately goes out of scope.
13198 ##### Example
13200     unique_lock<mutex>(m1);
13201     lock_guard<mutex> {m2};
13202     lock(m1, m2);
13204 This looks innocent enough, but it isn't.
13206 ##### Enforcement
13208 Flag all unnamed `lock_guard`s and `unique_lock`s.
13212 ### <a name="Rconc-mutex"></a>P.50: Define a `mutex` together with the data it guards. Use `synchronized_value<T>` where possible
13214 ##### Reason
13216 It should be obvious to a reader that the data is to be guarded and how. This decreases the chance of the wrong mutex being locked, or the mutex not being locked. 
13218 Using a `synchronized_value<T>` ensures that the data has a mutex, and the right mutex is locked when the data is accessed.
13219 See the [WG21 proposal](http://wg21.link/p0290)) to add `synchronized_value` to a future TS or revision of the C++ standard.
13221 ##### Example
13223     struct Record {
13224         std::mutex m;   // take this mutex before accessing other members
13225         // ...
13226     };
13228     class MyClass {
13229         struct DataRecord {
13230            // ...
13231         };
13232         synchronized_value<DataRecord> data; // Protect the data with a mutex
13233     };
13235 ##### Enforcement
13237 ??? Possible?
13240 ## <a name="SScp-par"></a>CP.par: Parallelism
13242 By "parallelism" we refer to performing a task (more or less) simultaneously ("in parallel with") on many data items.
13244 Parallelism rule summary:
13246 * ???
13247 * ???
13248 * Where appropriate, prefer the standard-library parallel algorithms
13249 * Use algorithms that are designed for parallelism, not algorithms with unnecessary dependency on linear evaluation
13253 ## <a name="SScp-mess"></a>CP.mess: Message passing
13255 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.
13256 Most people shouldn't work at this level: it's error-prone and development is slow.
13257 If possible, use a higher level facility: messaging libraries, parallel algorithms, and vectorization.
13258 This section looks at passing messages so that a programmer doesn't have to do explicit synchronization.
13260 Message passing rules summary:
13262 * [CP.60: Use a `future` to return a value from a concurrent task](#Rconc-future)
13263 * [CP.61: Use a `async()` to spawn a concurrent task](#Rconc-async)
13264 * message queues
13265 * messaging libraries
13267 ???? should there be a "use X rather than `std::async`" where X is something that would use a better specified thread pool?
13269 ??? 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?
13272 ### <a name="Rconc-future"></a>CP.60: Use a `future` to return a value from a concurrent task
13274 ##### Reason
13276 A `future` preserves the usual function call return semantics for asynchronous tasks.
13277 The is no explicit locking and both correct (value) return and error (exception) return are handled simply.
13279 ##### Example
13281     ???
13283 ##### Note
13287 ##### Enforcement
13291 ### <a name="Rconc-async"></a>CP.61: Use a `async()` to spawn a concurrent task
13293 ##### Reason
13295 A `future` preserves the usual function call return semantics for asynchronous tasks.
13296 The is no explicit locking and both correct (value) return and error (exception) return are handled simply.
13298 ##### Example
13300     ???
13302 ##### Note
13304 Unfortunately, `async()` is not perfect.
13305 For example, there is no guarantee that a thread pool is used to minimize thread construction.
13306 In fact, most current `async()` implementations don't.
13307 However, `async()` is simple and logically correct so until something better comes along
13308 and unless you really need to optimize for many asynchronous tasks, stick with `async()`.
13310 ##### Enforcement
13315 ## <a name="SScp-vec"></a>CP.vec: Vectorization
13317 Vectorization is a technique for executing a number of tasks concurrently without introducing explicit synchronization.
13318 An operation is simply applied to elements of a data structure (a vector, an array, etc.) in parallel.
13319 Vectorization has the interesting property of often requiring no non-local changes to a program.
13320 However, vectorization works best with simple data structures and with algorithms specifically crafted to enable it.
13322 Vectorization rule summary:
13324 * ???
13325 * ???
13327 ## <a name="SScp-free"></a>CP.free: Lock-free programming
13329 Synchronization using `mutex`es and `condition_variable`s can be relatively expensive.
13330 Furthermore, it can lead to deadlock.
13331 For performance and to eliminate the possibility of deadlock, we sometimes have to use the tricky low-level "lock-free" facilities
13332 that rely on briefly gaining exclusive ("atomic") access to memory.
13333 Lock free programming is also used to implement higher-level concurrency mechanisms, such as `thread`s and `mutex`es.
13335 Lock-free programming rule summary:
13337 * [CP.100: Don't use lock-free programming unless you absolutely have to](#Rconc-lockfree)
13338 * [CP.101: Distrust your hardware/compiler combination](#Rconc-distrust)
13339 * [CP.102: Carefully study the literature](#Rconc-literature)
13340 * how/when to use atomics
13341 * avoid starvation
13342 * use a lock free data structure rather than hand-crafting specific lock-free access
13343 * [CP.110: Do not write your own double-checked locking for initialization](#Rconc-double)
13344 * [CP.111: Use a conventional pattern if you really need double-checked locking](#Rconc-double-pattern)
13345 * how/when to compare and swap
13348 ### <a name="Rconc-lockfree"></a>CP.100: Don't use lock-free programming unless you absolutely have to
13350 ##### Reason
13352 It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures.
13354 ##### Example, bad
13356     extern atomic<Link*> head;        // the shared head of a linked list
13358     Link* nh = new Link(data, nullptr);    // make a link ready for insertion
13359     Link* h = head.load();                 // read the shared head of the list
13361     do {
13362         if (h->data <= data) break;        // if so, insert elsewhere
13363         nh->next = h;                      // next element is the previous head
13364     } while (!head.compare_exchange_weak(h, nh));    // write nh to head or to h
13366 Spot the bug.
13367 It would be really hard to find through testing.
13368 Read up on the ABA problem.
13370 ##### Exception
13372 [Atomic variables](#???) can be used simply and safely, as long as you are using the sequentially consistent memory model (memory_order_seq_cst), which is the default.
13374 ##### Note
13376 Higher-level concurrency mechanisms, such as `thread`s and `mutex`es are implemented using lock-free programming.
13378 **Alternative**: Use lock-free data structures implemented by others as part of some library.
13381 ### <a name="Rconc-distrust"></a>CP.101: Distrust your hardware/compiler combination
13383 ##### Reason
13385 The low-level hardware interfaces used by lock-free programming are among the hardest to implement well and among
13386 the areas where the most subtle portability problems occur.
13387 If you are doing lock-free programming for performance, you need to check for regressions.
13389 ##### Note
13391 Instruction reordering (static and dynamic) makes it hard for us to think effectively at this level (especially if you use relaxed memory models).
13392 Experience, (semi)formal models and model checking can be useful.
13393 Testing - often to an extreme extent - is essential.
13394 "Don't fly too close to the sun."
13396 ##### Enforcement
13398 Have strong rules for re-testing in place that covers any change in hardware, operating system, compiler, and libraries.
13401 ### <a name="Rconc-literature"></a>CP.102: Carefully study the literature
13403 ##### Reason
13405 With the exception of atomics and a few use standard patterns, lock-free programming is really an expert-only topic.
13406 Become an expert before shipping lock-free code for others to use.
13408 ##### References
13410 * Anthony Williams: C++ concurrency in action. Manning Publications.
13411 * Boehm, Adve, You Don't Know Jack About Shared Variables or Memory Models , Communications of the ACM, Feb 2012.
13412 * Boehm, "Threads Basics", HPL TR 2009-259.
13413 * Adve, Boehm, "Memory Models: A Case for Rethinking Parallel Languages and Hardware", Communications of the ACM, August 2010.
13414 * Boehm, Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 08.
13415 * Mark Batty, Scott Owens, Susmit Sarkar, Peter Sewell, and Tjark Weber, "Mathematizing C++ Concurrency", POPL 2011.
13416 * 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.
13417 * Damian Dechev and Bjarne Stroustrup: Scalable Non-blocking Concurrent Objects for Mission Critical Code. ACM OOPSLA'09. October 2009
13418 * 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.
13421 ### <a name="Rconc-double"></a>CP.110: Do not write your own double-checked locking for initialization
13423 ##### Reason
13425 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.
13427 ##### Example
13429 Example with std::call_once.
13431     void f()
13432     {
13433         static std::once_flag my_once_flag;
13434         std::call_once(my_once_flag, []()
13435         {
13436             // do this only once
13437         });
13438         // ...
13439     }
13441 Example with thread-safe static local variables of C++11.
13443     void f()
13444     {
13445         // Assuming the compiler is compliant with C++11
13446         static My_class my_object; // Constructor called only once
13447         // ...
13448     }
13450     class My_class
13451     {
13452     public:
13453         My_class()
13454         {
13455             // ...
13456         }
13457     };
13459 ##### Enforcement
13461 ??? Is it possible to detect the idiom?
13464 ### <a name="Rconc-double-pattern"></a>CP.111: Use a conventional pattern if you really need double-checked locking
13466 ##### Reason
13468 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.
13470 ##### Example, bad
13472 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.
13474     atomic<bool> x_init;
13476     if (!x_init.load(memory_order_acquire)) {
13477         lock_guard<mutex> lck(x_mutex);
13478         if (!x_init.load(memory_order_relaxed)) {
13479             // ... initialize x ...
13480             x_init.store(true, memory_order_release);
13481         }
13482     }
13484 ##### Example, good
13486 One of the conventional patterns is below.
13488     std::atomic<int> state;
13490     // If state == SOME_ACTION_NEEDED maybe an action is needed, maybe not, we need to
13491     // check again in a lock. However, if state != SOME_ACTION_NEEDED, then we can be
13492     // sure that an action is not needed. This is the basic assumption of double-checked
13493     // locking.
13495     if (state == SOME_ACTION_NEEDED)
13496     {
13497         std::lock_guard<std::mutex> lock(mutex);
13498         if (state == SOME_ACTION_NEEDED)
13499         {
13500             // do something
13501             state = NO_ACTION_NEEDED;
13502         }
13503     }
13505 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).
13507 ##### Enforcement
13509 ??? Is it possible to detect the idiom?
13512 ## <a name="SScp-etc"></a>CP.etc: Etc. concurrency rules
13514 These rules defy simple categorization:
13516 * [CP.200: Use `volatile` only to talk to non-C++ memory](#Rconc-volatile2)
13517 * [CP.201: ??? Signals](#Rconc-signal)
13519 ### <a name="Rconc-volatile2"></a>CP.200: Use `volatile` only to talk to non-C++ memory
13521 ##### Reason
13523 `volatile` is used to refer to objects that are shared with "non-C++" code or hardware that does not follow the C++ memory model.
13525 ##### Example
13527     const volatile long clock;
13529 This describes a register constantly updated by a clock circuit.
13530 `clock` is `volatile` because its value will change without any action from the C++ program that uses it.
13531 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:
13533     long t1 = clock;
13534     // ... no use of clock here ...
13535     long t2 = clock;
13537 `clock` is `const` because the program should not try to write to `clock`.
13539 ##### Note
13541 Unless you are writing the lowest level code manipulating hardware directly, consider `volatile` an esoteric feature that is best avoided.
13543 ##### Example
13545 Usually C++ code receives `volatile` memory that is owned Elsewhere (hardware or another language):
13547     int volatile* vi = get_hardware_memory_location();
13548         // note: we get a pointer to someone else's memory here
13549         // volatile says "treat this with extra respect"
13551 Sometimes C++ code allocates the `volatile` memory and shares it with "elsewhere" (hardware or another language) by deliberately escaping a pointer:
13553     static volatile long vl;
13554     please_use_this(&vl);   // escape a reference to this to "elsewhere" (not C++)
13556 ##### Example; bad
13558 `volatile` local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral?
13559 The same applies almost as strongly to member variables, for the same reason.
13561     void f() {
13562         volatile int i = 0; // bad, volatile local variable
13563         // etc.
13564     }
13566     class My_type {
13567         volatile int i = 0; // suspicious, volatile member variable
13568         // etc.
13569     };
13571 ##### Note
13573 In C++, unlike in some other languages, `volatile` has [nothing to do with synchronization](#Rconc-volatile).
13575 ##### Enforcement
13577 * Flag `volatile T` local and member variables; almost certainly you intended to use `atomic<T>` instead.
13578 * ???
13580 ### <a name="Rconc-signal"></a>CP.201: ??? Signals
13582 ???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")
13585 # <a name="S-errors"></a>E: Error handling
13587 Error handling involves:
13589 * Detecting an error
13590 * Transmitting information about an error to some handler code
13591 * Preserve the state of a program in a valid state
13592 * Avoid resource leaks
13594 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.
13596 The rules are designed to help avoid several kinds of errors:
13598 * Type violations (e.g., misuse of `union`s and casts)
13599 * Resource leaks (including memory leaks)
13600 * Bounds errors
13601 * Lifetime errors (e.g., accessing an object after is has been `delete`d)
13602 * Complexity errors (logical errors make likely by overly complex expression of ideas)
13603 * Interface errors (e.g., an unexpected value is passed through an interface)
13605 Error-handling rule summary:
13607 * [E.1: Develop an error-handling strategy early in a design](#Re-design)
13608 * [E.2: Throw an exception to signal that a function can't perform its assigned task](#Re-throw)
13609 * [E.3: Use exceptions for error handling only](#Re-errors)
13610 * [E.4: Design your error-handling strategy around invariants](#Re-design-invariants)
13611 * [E.5: Let a constructor establish an invariant, and throw if it cannot](#Re-invariant)
13612 * [E.6: Use RAII to prevent leaks](#Re-raii)
13613 * [E.7: State your preconditions](#Re-precondition)
13614 * [E.8: State your postconditions](#Re-postcondition)
13616 * [E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable](#Re-noexcept)
13617 * [E.13: Never throw while being the direct owner of an object](#Re-never-throw)
13618 * [E.14: Use purpose-designed user-defined types as exceptions (not built-in types)](#Re-exception-types)
13619 * [E.15: Catch exceptions from a hierarchy by reference](#Re-exception-ref)
13620 * [E.16: Destructors, deallocation, and `swap` must never fail](#Re-never-fail)
13621 * [E.17: Don't try to catch every exception in every function](#Re-not-always)
13622 * [E.18: Minimize the use of explicit `try`/`catch`](#Re-catch)
13623 * [E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available](#Re-finally)
13625 * [E.25: If you can't throw exceptions, simulate RAII for resource management](#Re-no-throw-raii)
13626 * [E.26: If you can't throw exceptions, consider failing fast](#Re-no-throw-crash)
13627 * [E.27: If you can't throw exceptions, use error codes systematically](#Re-no-throw-codes)
13628 * [E.28: Avoid error handling based on global state (e.g. `errno`)](#Re-no-throw)
13630 * [E.30: Don't use exception specifications](#Re-specifications)
13631 * [E.31: Properly order your `catch`-clauses](#Re_catch)
13633 ### <a name="Re-design"></a>E.1: Develop an error-handling strategy early in a design
13635 ##### Reason
13637 A consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system.
13639 ### <a name="Re-throw"></a>E.2: Throw an exception to signal that a function can't perform its assigned task
13641 ##### Reason
13643 To make error handling systematic, robust, and non-repetitive.
13645 ##### Example
13647     struct Foo {
13648         vector<Thing> v;
13649         File_handle f;
13650         string s;
13651     };
13653     void use()
13654     {
13655         Foo bar {{Thing{1}, Thing{2}, Thing{monkey}}, {"my_file", "r"}, "Here we go!"};
13656         // ...
13657     }
13659 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.
13660 In each case, they throw an exception for `use()`'s caller to handle.
13661 If `use()` could handle the failure to construct `bar` it can take control using `try`/`catch`.
13662 In either case, `Foo`'s constructor correctly destroys constructed members before passing control to whatever tried to create a `Foo`.
13663 Note that there is no return value that could contain an error code.
13665 The `File_handle` constructor might be defined like this:
13667     File_handle::File_handle(const string& name, const string& mode)
13668         :f{fopen(name.c_str(), mode.c_str())}
13669     {
13670         if (!f)
13671             throw runtime_error{"File_handle: could not open " + name + " as " + mode};
13672     }
13674 ##### Note
13676 It is often said that exceptions are meant to signal exceptional events and failures.
13677 However, that's a bit circular because "what is exceptional?"
13678 Examples:
13680 * A precondition that cannot be met
13681 * A constructor that cannot construct an object (failure to establish its class's [invariant](#Rc-struct))
13682 * An out-of-range error (e.g., `v[v.size()] = 7`)
13683 * Inability to acquire a resource (e.g., the network is down)
13685 In contrast, termination of an ordinary loop is not exceptional.
13686 Unless the loop was meant to be infinite, termination is normal and expected.
13688 ##### Note
13690 Don't use a `throw` as simply an alternative way of returning a value from a function.
13692 ##### Exception
13694 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`.
13696 **See also**: [RAII](#Re-raii)
13698 **See also**: [discussion](#Sd-noexcept)
13700 ##### Note
13702 Before deciding that you cannot afford or don't like exception-based error handling, have a look at the [alternatives](#Re-no-throw-raii);
13703 they have their own complexities and problems.
13704 Also, as far as possible, measure before making claims about efficiency.
13706 ### <a name="Re-errors"></a>E.3: Use exceptions for error handling only
13708 ##### Reason
13710 To keep error handling separated from "ordinary code."
13711 C++ implementations tend to be optimized based on the assumption that exceptions are rare.
13713 ##### Example, don't
13715     // don't: exception not used for error handling
13716     int find_index(vector<string>& vec, const string& x)
13717     {
13718         try {
13719             for (int i = 0; i < vec.size(); ++i)
13720                 if (vec[i] == x) throw i;  // found x
13721         } catch (int i) {
13722             return i;
13723         }
13724         return -1;   // not found
13725     }
13727 This is more complicated and most likely runs much slower than the obvious alternative.
13728 There is nothing exceptional about finding a value in a `vector`.
13730 ##### Enforcement
13732 Would need to be heuristic.
13733 Look for exception values "leaked" out of `catch` clauses.
13735 ### <a name="Re-design-invariants"></a>E.4: Design your error-handling strategy around invariants
13737 ##### Reason
13739 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.
13741 ##### Note
13743 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.
13745 ##### Enforcement
13749 ### <a name="Re-invariant"></a>E.5: Let a constructor establish an invariant, and throw if it cannot
13751 ##### Reason
13753 Leaving an object without its invariant established is asking for trouble.
13754 Not all member functions can be called.
13756 ##### Example
13758     class Vector {  // very simplified vector of doubles
13759         // if elem != nullptr then elem points to sz doubles
13760     public:
13761         Vector() : elem{nullptr}, sz{0}{}
13762         Vector(int s) : elem{new double}, sz{s} { /* initialize elements */ }
13763         ~Vector() { delete elem; }
13764         double& operator[](int s) { return elem[s]; }
13765         // ...
13766     private:
13767         owner<double*> elem;
13768         int sz;
13769     };
13771 The class invariant - here stated as a comment - is established by the constructors.
13772 `new` throws if it cannot allocate the required memory.
13773 The operators, notably the subscript operator, relies on the invariant.
13775 **See also**: [If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
13777 ##### Enforcement
13779 Flag classes with `private` state without a constructor (public, protected, or private).
13781 ### <a name="Re-raii"></a>E.6: Use RAII to prevent leaks
13783 ##### Reason
13785 Leaks are typically unacceptable.
13786 Manual resource release is error-prone.
13787 RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.
13789 ##### Example
13791     void f1(int i)   // Bad: possibly leak
13792     {
13793         int* p = new int[12];
13794         // ...
13795         if (i < 17) throw Bad {"in f()", i};
13796         // ...
13797     }
13799 We could carefully release the resource before the throw:
13801     void f2(int i)   // Clumsy and error-prone: explicit release
13802     {
13803         int* p = new int[12];
13804         // ...
13805         if (i < 17) {
13806             delete[] p;
13807             throw Bad {"in f()", i};
13808         }
13809         // ...
13810     }
13812 This is verbose. In larger code with multiple possible `throw`s explicit releases become repetitive and error-prone.
13814     void f3(int i)   // OK: resource management done by a handle (but see below)
13815     {
13816         auto p = make_unique<int[]>(12);
13817         // ...
13818         if (i < 17) throw Bad {"in f()", i};
13819         // ...
13820     }
13822 Note that this works even when the `throw` is implicit because it happened in a called function:
13824     void f4(int i)   // OK: resource management done by a handle (but see below)
13825     {
13826         auto p = make_unique<int[]>(12);
13827         // ...
13828         helper(i);   // may throw
13829         // ...
13830     }
13832 Unless you really need pointer semantics, use a local resource object:
13834     void f5(int i)   // OK: resource management done by local object
13835     {
13836         vector<int> v(12);
13837         // ...
13838         helper(i);   // may throw
13839         // ...
13840     }
13842 That's even simpler and safer, and often more efficient.
13844 ##### Note
13846 If there is no obvious resource handle and for some reason defining a proper RAII object/handle is infeasible,
13847 as a last resort, cleanup actions can be represented by a [`final_action`](#Re-finally) object.
13849 ##### Note
13851 But what do we do if we are writing a program where exceptions cannot be used?
13852 First challenge that assumption; there are many anti-exceptions myths around.
13853 We know of only a few good reasons:
13855 * We are on a system so small that the exception support would eat up most of our 2K memory.
13856 * 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.
13857 * We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways
13858   (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
13859 * Our implementation of the C++ exception mechanisms is unreasonably poor
13860 (slow, memory consuming, failing to work correctly for dynamically linked libraries, etc.).
13861 Complain to your implementation purveyor; if no user complains, no improvement will happen.
13862 * We get fired if we challenge our manager's ancient wisdom.
13864 Only the first of these reasons is fundamental, so whenever possible, use exceptions to implement RAII, or design your RAII objects to never fail.
13865 When exceptions cannot be used, simulate RAII.
13866 That is, systematically check that objects are valid after construction and still release all resources in the destructor.
13867 One strategy is to add a `valid()` operation to every resource handle:
13869     void f()
13870     {
13871         vector<string> vs(100);   // not std::vector: valid() added
13872         if (!vs.valid()) {
13873             // handle error or exit
13874         }
13876         ifstream fs("foo");   // not std::ifstream: valid() added
13877         if (!fs.valid()) {
13878             // handle error or exit
13879         }
13881         // ...
13882     } // destructors clean up as usual
13884 Obviously, this increases the size of the code, doesn't allow for implicit propagation of "exceptions" (`valid()` checks), and `valid()` checks can be forgotten.
13885 Prefer to use exceptions.
13887 **See also**: [Use of `noexcept`](#Se-noexcept).
13889 ##### Enforcement
13893 ### <a name="Re-precondition"></a>E.7: State your preconditions
13895 ##### Reason
13897 To avoid interface errors.
13899 **See also**: [precondition rule](#Ri-pre).
13901 ### <a name="Re-postcondition"></a>E.8: State your postconditions
13903 ##### Reason
13905 To avoid interface errors.
13907 **See also**: [postcondition rule](#Ri-post).
13909 ### <a name="Re-noexcept"></a>E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable
13911 ##### Reason
13913 To make error handling systematic, robust, and efficient.
13915 ##### Example
13917     double compute(double d) noexcept
13918     {
13919         return log(sqrt(d <= 0 ? 1 : d));
13920     }
13922 Here, we know that `compute` will not throw because it is composed out of operations that don't throw.
13923 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`.
13925 ##### Note
13927 Many standard library functions are `noexcept` including all the standard library functions "inherited" from the C standard library.
13929 ##### Example
13931     vector<double> munge(const vector<double>& v) noexcept
13932     {
13933         vector<double> v2(v.size());
13934         // ... do something ...
13935     }
13937 The `noexcept` here states that I am not willing or able to handle the situation where I cannot construct the local `vector`.
13938 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.
13940 ##### Note
13942 Do not use traditional [exception-specifications](#Re-specifications).
13944 ##### See also
13946 [discussion](#Sd-noexcept).
13948 ### <a name="Re-never-throw"></a>E.13: Never throw while being the direct owner of an object
13950 ##### Reason
13952 That would be a leak.
13954 ##### Example
13956     void leak(int x)   // don't: may leak
13957     {
13958         auto p = new int{7};
13959         if (x < 0) throw Get_me_out_of_here{};  // may leak *p
13960         // ...
13961         delete p;   // we may never get here
13962     }
13964 One way of avoiding such problems is to use resource handles consistently:
13966     void no_leak(int x)
13967     {
13968         auto p = make_unique<int>(7);
13969         if (x < 0) throw Get_me_out_of_here{};  // will delete *p if necessary
13970         // ...
13971         // no need for delete p
13972     }
13974 Another solution (often better) would be to use a local variable to eliminate explicit use of pointers:
13976     void no_leak_simplified(int x)
13977     {
13978         vector<int> v(7);
13979         // ...
13980     }
13982 ##### Note
13984 If you have local "things" that requires cleanup, but is not represented by an object with a destructor, such cleanup must
13985 also be done before a `throw`.
13986 Sometimes, [`finally()`](#Re-finally) can make such unsystematic cleanup a bit more manageable.
13988 ### <a name="Re-exception-types"></a>E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
13990 ##### Reason
13992 A user-defined type is unlikely to clash with other people's exceptions.
13994 ##### Example
13996     void my_code()
13997     {
13998         // ...
13999         throw Moonphase_error{};
14000         // ...
14001     }
14003     void your_code()
14004     {
14005         try {
14006             // ...
14007             my_code();
14008             // ...
14009         }
14010         catch(Bufferpool_exhausted) {
14011             // ...
14012         }
14013     }
14015 ##### Example, don't
14017     void my_code()     // Don't
14018     {
14019         // ...
14020         throw 7;       // 7 means "moon in the 4th quarter"
14021         // ...
14022     }
14024     void your_code()   // Don't
14025     {
14026         try {
14027             // ...
14028             my_code();
14029             // ...
14030         }
14031         catch(int i) {  // i == 7 means "input buffer too small"
14032             // ...
14033         }
14034     }
14036 ##### Note
14038 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.
14040 ##### Example, don't
14042     void my_code()   // Don't
14043     {
14044         // ...
14045         throw runtime_error{"moon in the 4th quarter"};
14046         // ...
14047     }
14049     void your_code()   // Don't
14050     {
14051         try {
14052             // ...
14053             my_code();
14054             // ...
14055         }
14056         catch(runtime_error) {   // runtime_error means "input buffer too small"
14057             // ...
14058         }
14059     }
14061 **See also**: [Discussion](#Sd-???)
14063 ##### Enforcement
14065 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.
14067 ### <a name="Re-exception-ref"></a>E.15: Catch exceptions from a hierarchy by reference
14069 ##### Reason
14071 To prevent slicing.
14073 ##### Example
14075     void f()
14076     try {
14077         // ...
14078     }
14079     catch (exception e) {   // don't: may slice
14080         // ...
14081     }
14083 Instead, use:
14085     catch (exception& e) { /* ... */ }
14087 ##### Enforcement
14089 Flag by-value exceptions if their types are part of a hierarchy (could require whole-program analysis to be perfect).
14091 ### <a name="Re-never-fail"></a>E.16: Destructors, deallocation, and `swap` must never fail
14093 ##### Reason
14095 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.
14097 ##### Example, don't
14099     class Connection {
14100         // ...
14101     public:
14102         ~Connection()   // Don't: very bad destructor
14103         {
14104             if (cannot_disconnect()) throw I_give_up{information};
14105             // ...
14106         }
14107     };
14109 ##### Note
14111 Many have tried to write reliable code violating this rule for examples, such as a network connection that "refuses to close".
14112 To the best of our knowledge nobody has found a general way of doing this.
14113 Occasionally, for very specific examples, you can get away with setting some state for future cleanup.
14114 For example, we might put a socket that does not want to close on a "bad socket" list,
14115 to be examined by a regular sweep of the system state.
14116 Every example we have seen of this is error-prone, specialized, and often buggy.
14118 ##### Note
14120 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.
14122 ##### Note
14124 Deallocation functions, including `operator delete`, must be `noexcept`. `swap` functions must be `noexcept`.
14125 Most destructors are implicitly `noexcept` by default.
14126 Also, [make move operations `noexcept`](##Rc-move-noexcept).
14128 ##### Enforcement
14130 Catch destructors, deallocation operations, and `swap`s that `throw`.
14131 Catch such operations that are not `noexcept`.
14133 **See also**: [discussion](#Sd-never-fail)
14135 ### <a name="Re-not-always"></a>E.17: Don't try to catch every exception in every function
14137 ##### Reason
14139 Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste.
14140 Let an exception propagate until it reaches a function that can handle it.
14141 Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii).
14143 ##### Example, don't
14145     void f()   // bad
14146     {
14147         try {
14148             // ...
14149         }
14150         catch (...) {
14151             // no action
14152             throw;   // propagate exception
14153         }
14154     }
14156 ##### Enforcement
14158 * Flag nested try-blocks.
14159 * Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high")
14161 ### <a name="Re-catch"></a>E.18: Minimize the use of explicit `try`/`catch`
14163 ##### Reason
14165  `try`/`catch` is verbose and non-trivial uses error-prone.
14166  `try`/`catch` can be a sign of unsystematic and/or low-level resource management or error handling.
14168 ##### Example, Bad
14170     void f(zstring s)
14171     {
14172         Gadget* p;
14173         try {
14174             p = new Gadget(s);
14175             // ...
14176             delete p;
14177         }
14178         catch (Gadget_construction_failure) {
14179             delete p;
14180             throw;
14181         }
14182     }
14184 This code is messy.
14185 There could be a leak from the naked pointer in the `try` block.
14186 Not all exceptions are handled.
14187 `deleting` an object that failed to construct is almost certainly a mistake.
14188 Better:
14190     void f2(zstring s)
14191     {
14192         Gadget g {s};
14193     }
14195 ##### Alternatives
14197 * proper resource handles and [RAII](#Re-raii)
14198 * [`finally`](#Re-finally)
14200 ##### Enforcement
14202 ??? hard, needs a heuristic
14204 ### <a name="Re-finally"></a>E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available
14206 ##### Reason
14208 `finally` is less verbose and harder to get wrong than `try`/`catch`.
14210 ##### Example
14212     void f(int n)
14213     {
14214         void* p = malloc(1, n);
14215         auto _ = finally([p] { free(p); });
14216         // ...
14217     }
14219 ##### Note
14221 `finally` is not as messy as `try`/`catch`, but it is still ad-hoc.
14222 Prefer [proper resource management objects](#Re-raii).
14223 Consider `finally` a last resort.
14225 ##### Note
14227 Use of `finally` is a systematic and reasonably clean alternative to the old [`goto exit;` technique](##Re-no-throw-codes)
14228 for dealing with cleanup where resource management is not systematic.
14230 ##### Enforcement
14232 Heuristic: Detect `goto exit;`
14234 ### <a name="Re-no-throw-raii"></a>E.25: If you can't throw exceptions, simulate RAII for resource management
14236 ##### Reason
14238 Even without exceptions, [RAII](#Re-raii) is usually the best and most systematic way of dealing with resources.
14240 ##### Note
14242 Error handling using exceptions is the only complete and systematic way of handling non-local errors in C++.
14243 In particular, non-intrusively signaling failure to construct an object requires an exception.
14244 Signaling errors in a way that cannot be ignored requires exceptions.
14245 If you can't use exceptions, simulate their use as best you can.
14247 A lot of fear of exceptions is misguided.
14248 When used for exceptional circumstances in code that is not littered with pointers and complicated control structures,
14249 exception handling is almost always affordable (in time and space) and almost always leads to better code.
14250 This, of course, assumes a good implementation of the exception handling mechanisms, which is not available on all systems.
14251 There are also cases where the problems above do not apply, but exceptions cannot be used for other reasons.
14252 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.
14253 In the absence of appropriate time estimation tools, this is hard to guarantee for exceptions.
14254 Such systems (e.g. flight control software) typically also ban the use of dynamic (heap) memory.
14256 So, the primary guideline for error handling is "use exceptions and [RAII](#Re-raii)."
14257 This section deals with the cases where you either do not have an efficient implementation of exceptions,
14258 or have such a rat's nest of old-style code
14259 (e.g., lots of pointers, ill-defined ownership, and lots of unsystematic error handling based on tests of error codes)
14260 that it is infeasible to introduce simple and systematic exception handling.
14262 Before condemning exceptions or complaining too much about their cost, consider examples of the use of [error codes](#Re-no-throw-codes).
14263 Consider the cost and complexity of the use of error codes.
14264 If performance is your worry, measure.
14266 ##### Example
14268 Assume you wanted to write
14270     void func(zstring arg)
14271     {
14272         Gadget g {arg};
14273         // ...
14274     }
14276 If the `gadget` isn't correctly constructed, `func` exits with an exception.
14277 If we cannot throw an exception, we can simulate this RAII style of resource handling by adding a `valid()` member function to `Gadget`:
14279     error_indicator func(zstring arg)
14280     {
14281         Gadget g {arg};
14282         if (!g.valid()) return gadget_construction_error;
14283         // ...
14284         return 0;   // zero indicates "good"
14285     }
14287 The problem is of course that the caller now has to remember to test the return value.
14289 **See also**: [Discussion](#Sd-???).
14291 ##### Enforcement
14293 Possible (only) for specific versions of this idea: e.g., test for systematic test of `valid()` after resource handle construction
14295 ### <a name="Re-no-throw-crash"></a>E.26: If you can't throw exceptions, consider failing fast
14297 ##### Reason
14299 If you can't do a good job at recovering, at least you can get out before too much consequential damage is done.
14301 See also [Simulating RAII](#Re-no-throw-raii).
14303 ##### Note
14305 If you cannot be systematic about error handling, consider "crashing" as a response to any error that cannot be handled locally.
14306 That is, if you cannot recover from an error in the context of the function that detected it, call `abort()`, `quick_exit()`,
14307 or a similar function that will trigger some sort of system restart.
14309 In systems where you have lots of processes and/or lots of computers, you need to expect and handle fatal crashes anyway,
14310 say from hardware failures.
14311 In such cases, "crashing" is simply leaving error handling to the next level of the system.
14313 ##### Example
14315     void f(int n)
14316     {
14317         // ...
14318         p = static_cast<X*>(malloc(n, X));
14319         if (p == nullptr) abort();     // abort if memory is exhausted
14320         // ...
14321     }
14323 Most programs cannot handle memory exhaustion gracefully anyway. This is roughly equivalent to
14325     void f(int n)
14326     {
14327         // ...
14328         p = new X[n];    // throw if memory is exhausted (by default, terminate)
14329         // ...
14330     }
14332 Typically, it is a good idea to log the reason for the "crash" before exiting.
14334 ##### Enforcement
14336 Awkward
14338 ### <a name="Re-no-throw-codes"></a>E.27: If you can't throw exceptions, use error codes systematically
14340 ##### Reason
14342 Systematic use of any error-handling strategy minimizes the chance of forgetting to handle an error.
14344 See also [Simulating RAII](#Re-no-throw-raii).
14346 ##### Note
14348 There are several issues to be addressed:
14350 * how do you transmit an error indicator from out of a function?
14351 * how do you release all resources from a function before doing an error exit?
14352 * What do you use as an error indicator?
14354 In general, returning an error indicator implies returning two values: The result and an error indicator.
14355 The error indicator can be part of the object, e.g. an object can have a `valid()` indicator
14356 or a pair of values can be returned.
14358 ##### Example
14360     Gadget make_gadget(int n)
14361     {
14362         // ...
14363     }
14365     void user()
14366     {
14367         Gadget g = make_gadget(17);
14368         if (!g.valid()) {
14369                 // error handling
14370         }
14371         // ...
14372     }
14374 This approach fits with [simulated RAII resource management](#Re-no-throw-raii).
14375 The `valid()` function could return an `error_indicator` (e.g. a member of an `error_indicator` enumeration).
14377 ##### Example
14379 What if we cannot or do not want to modify the `Gadget` type?
14380 In that case, we must return a pair of values.
14381 For example:
14383     std::pair<Gadget, error_indicator> make_gadget(int n)
14384     {
14385         // ...
14386     }
14388     void user()
14389     {
14390         auto r = make_gadget(17);
14391         if (!r.second) {
14392                 // error handling
14393         }
14394         Gadget& g = r.first;
14395         // ...
14396     }
14398 As shown, `std::pair` is a possible return type.
14399 Some people prefer a specific type.
14400 For example:
14402     Gval make_gadget(int n)
14403     {
14404         // ...
14405     }
14407     void user()
14408     {
14409         auto r = make_gadget(17);
14410         if (!r.err) {
14411                 // error handling
14412         }
14413         Gadget& g = r.val;
14414         // ...
14415     }
14417 One reason to prefer a specific return type is to have names for its members, rather than the somewhat cryptic `first` and `second`
14418 and to avoid confusion with other uses of `std::pair`.
14420 ##### Example
14422 In general, you must clean up before an error exit.
14423 This can be messy:
14425     std::pair<int, error_indicator> user()
14426     {
14427         Gadget g1 = make_gadget(17);
14428         if (!g1.valid()) {
14429                 return {0, g1_error};
14430         }
14432         Gadget g2 = make_gadget(17);
14433         if (!g2.valid()) {
14434                 cleanup(g1);
14435                 return {0, g2_error};
14436         }
14438         // ...
14440         if (all_foobar(g1, g2)) {
14441             cleanup(g1);
14442             cleanup(g2);
14443             return {0, foobar_error};
14444         // ...
14446         cleanup(g1);
14447         cleanup(g2);
14448         return {res, 0};
14449     }
14451 Simulating RAII can be non-trivial, especially in functions with multiple resources and multiple possible errors.
14452 A not uncommon technique is to gather cleanup at the end of the function to avoid repetition:
14454     std::pair<int, error_indicator> user()
14455     {
14456         error_indicator err = 0;
14458         Gadget g1 = make_gadget(17);
14459         if (!g1.valid()) {
14460                 err = g1_error;
14461                 goto exit;
14462         }
14464         Gadget g2 = make_gadget(17);
14465         if (!g2.valid()) {
14466                 err = g2_error;
14467                 goto exit;
14468         }
14470         if (all_foobar(g1, g2)) {
14471             err = foobar_error;
14472             goto exit;
14473         }
14474         // ...
14476     exit:
14477       if (g1.valid()) cleanup(g1);
14478       if (g2.valid()) cleanup(g2);
14479       return {res, err};
14480     }
14482 The larger the function, the more tempting this technique becomes.
14483 `finally` can [ease the pain a bit](#Re-finally).
14484 Also, the larger the program becomes the harder it is to apply an error-indicator-based error handling strategy systematically.
14486 We [prefer exception-based error handling](#Re-throw) and recommend [keeping functions short](#Rf-single).
14488 **See also**: [Discussion](#Sd-???).
14490 **See also**: [Returning multiple values](#Rf-out-multi).
14492 ##### Enforcement
14494 Awkward.
14496 ### <a name="Re-no-throw"></a>E.28: Avoid error handling based on global state (e.g. `errno`)
14498 ##### Reason
14500 Global state is hard to manage and it is easy to forget to check it.
14501 When did you last test the return value of `printf()`?
14503 See also [Simulating RAII](#Re-no-throw-raii).
14505 ##### Example, bad
14507     ???
14509 ##### Note
14511 C-style error handling is based on the global variable `errno`, so it is essentially impossible to avoid this style completely.
14513 ##### Enforcement
14515 Awkward.
14518 ### <a name="Re-specifications"></a>E.30: Don't use exception specifications
14520 ##### Reason
14522 Exception specifications make error handling brittle, impose a run-time cost, and have been removed from the C++ standard.
14524 ##### Example
14526     int use(int arg)
14527         throw(X, Y)
14528     {
14529         // ...
14530         auto x = f(arg);
14531         // ...
14532     }
14534 if `f()` throws an exception different from `X` and `Y` the unexpected handler is invoked, which by default terminates.
14535 That's OK, but say that we have checked that this cannot happen and `f` is changed to throw a new exception `Z`,
14536 we now have a crash on our hands unless we change `use()` (and re-test everything).
14537 The snag is that `f()` may be in a library we do not control and the new exception is not anything that `use()` can do
14538 anything about or is in any way interested in.
14539 We can change `use()` to pass `Z` through, but now `use()`'s callers probably needs to be modified.
14540 This quickly becomes unmanageable.
14541 Alternatively, we can add a `try`-`catch` to `use()` to map `Z` into an acceptable exception.
14542 This too, quickly becomes unmanageable.
14543 Note that changes to the set of exceptions often happens at the lowest level of a system
14544 (e.g., because of changes to a network library or some middleware), so changes "bubble up" through long call chains.
14545 In a large code base, this could mean that nobody could update to a new version of a library until the last user was modified.
14546 If `use()` is part of a library, it may not be possible to update it because a change could affect unknown clients.
14548 The policy of letting exceptions propagate until they reach a function that potentially can handle it has proven itself over the years.
14550 ##### Note
14552 No. This would not be any better had exception specifications been statically enforced.
14553 For example, see [Stroustrup94](#Stroustrup94).
14555 ##### Note
14557 If no exception may be thrown, use [`noexcept`](#Re-noexcept) or its equivalent `throw()`.
14559 ##### Enforcement
14561 Flag every exception specification.
14563 ### <a name="Re_catch"></a>E.31: Properly order your `catch`-clauses
14565 ##### Reason
14567 `catch`-clauses are evaluated in the order they appear and one clause can hide another.
14569 ##### Example
14571     void f()
14572     {
14573         // ...
14574         try {
14575                 // ...
14576         }
14577         catch (Base& b) { /* ... */ }
14578         catch (Derived& d) { /* ... */ }
14579         catch (...) { /* ... */ }
14580         catch (std::exception& e){ /* ... */ }
14581     }
14583 If `Derived`is derived from `Base` the `Derived`-handler will never be invoked.
14584 The "catch everything" handler ensured that the `std::exception`-handler will never be invoked.
14586 ##### Enforcement
14588 Flag all "hiding handlers".
14590 # <a name="S-const"></a>Con: Constants and Immutability
14592 You can't have a race condition on a constant.
14593 It is easier to reason about a program when many of the objects cannot change their values.
14594 Interfaces that promises "no change" of objects passed as arguments greatly increase readability.
14596 Constant rule summary:
14598 * [Con.1: By default, make objects immutable](#Rconst-immutable)
14599 * [Con.2: By default, make member functions `const`](#Rconst-fct)
14600 * [Con.3: By default, pass pointers and references to `const`s](#Rconst-ref)
14601 * [Con.4: Use `const` to define objects with values that do not change after construction](#Rconst-const)
14602 * [Con.5: Use `constexpr` for values that can be computed at compile time](#Rconst-constexpr)
14604 ### <a name="Rconst-immutable"></a>Con.1: By default, make objects immutable
14606 ##### Reason
14608 Immutable objects are easier to reason about, so make objects non-`const` only when there is a need to change their value.
14609 Prevents accidental or hard-to-notice change of value.
14611 ##### Example
14613     for (const int i : c) cout << i << '\n';    // just reading: const
14615     for (int i : c) cout << i << '\n';          // BAD: just reading
14617 ##### Exception
14619 Function arguments are rarely mutated, but also rarely declared const.
14620 To avoid confusion and lots of false positives, don't enforce this rule for function arguments.
14622     void f(const char* const p); // pedantic
14623     void g(const int i);        // pedantic
14625 Note that function parameter is a local variable so changes to it are local.
14627 ##### Enforcement
14629 * Flag non-const variables that are not modified (except for parameters to avoid many false positives)
14631 ### <a name="Rconst-fct"></a>Con.2: By default, make member functions `const`
14633 ##### Reason
14635 A member function should be marked `const` unless it changes the object's observable state.
14636 This gives a more precise statement of design intent, better readability, more errors caught by the compiler, and sometimes more optimization opportunities.
14638 ##### Example; bad
14640     class Point {
14641         int x, y;
14642     public:
14643         int getx() { return x; }    // BAD, should be const as it doesn't modify the object's state
14644         // ...
14645     };
14647     void f(const Point& pt) {
14648         int x = pt.getx();          // ERROR, doesn't compile because getx was not marked const
14649     }
14651 ##### Note
14653 It is not inherently bad to pass a pointer or reference to non-const,
14654 but that should be done only when the called function is supposed to modify the object.
14655 A reader of code must assume that a function that takes a "plain" `T*` or `T&` will modify the object referred to.
14656 If it doesn't now, it might do so later without forcing recompilation.
14658 ##### Note
14660 There are code/libraries that are offer functions that declare a`T*` even though
14661 those function do not modify that `T`.
14662 This is a problem for people modernizing code.
14663 You can
14665 * update the library to be `const`-correct; preferred long-term solution
14666 * "cast away `const`"; [best avoided](#Res-casts-const)
14667 * provide a wrapper function
14669 Example:
14671     void f(int* p);   // old code: f() does not modify `*p`
14672     void f(const int* p) { f(const_cast<int*>(p); } // wrapper
14674 Note that this wrapper solution is a patch that should be used only when the declaration of `f()` cannot be be modified,
14675 e.g. because it is in a library that you cannot modify.
14678 ##### Enforcement
14680 * Flag a member function that is not marked `const`, but that does not perform a non-`const` operation on any member variable.
14682 ### <a name="Rconst-ref"></a>Con.3: By default, pass pointers and references to `const`s
14684 ##### Reason
14686  To avoid a called function unexpectedly changing the value.
14687  It's far easier to reason about programs when called functions don't modify state.
14689 ##### Example
14691     void f(char* p);        // does f modify *p? (assume it does)
14692     void g(const char* p);  // g does not modify *p
14694 ##### Note
14696 It is not inherently bad to pass a pointer or reference to non-const,
14697 but that should be done only when the called function is supposed to modify the object.
14699 ##### Note
14701 [Do not cast away `const`](#Res-casts-const).
14703 ##### Enforcement
14705 * Flag function that does not modify an object passed by  pointer or reference to non-`const`
14706 * Flag a function that (using a cast) modifies an object passed by pointer or reference to `const`
14708 ### <a name="Rconst-const"></a>Con.4: Use `const` to define objects with values that do not change after construction
14710 ##### Reason
14712  Prevent surprises from unexpectedly changed object values.
14714 ##### Example
14716     void f()
14717     {
14718         int x = 7;
14719         const int y = 9;
14721         for (;;) {
14722             // ...
14723         }
14724         // ...
14725     }
14727 As `x` is not `const`, we must assume that it is modified somewhere in the loop.
14729 ##### Enforcement
14731 * Flag unmodified non-`const` variables.
14733 ### <a name="Rconst-constexpr"></a>Con.5: Use `constexpr` for values that can be computed at compile time
14735 ##### Reason
14737 Better performance, better compile-time checking, guaranteed compile-time evaluation, no possibility of race conditions.
14739 ##### Example
14741     double x = f(2);            // possible run-time evaluation
14742     const double y = f(2);      // possible run-time evaluation
14743     constexpr double z = f(2);  // error unless f(2) can be evaluated at compile time
14745 ##### Note
14747 See F.4.
14749 ##### Enforcement
14751 * Flag `const` definitions with constant expression initializers.
14753 # <a name="S-templates"></a>T: Templates and generic programming
14755 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
14756 In C++, generic programming is supported by the `template` language mechanisms.
14758 Arguments to generic functions are characterized by sets of requirements on the argument types and values involved.
14759 In C++, these requirements are expressed by compile-time predicates called concepts.
14761 Templates can also be used for meta-programming; that is, programs that compose code at compile time.
14763 A central notion in generic programming is "concepts"; that is, requirements on template arguments presented as compile-time predicates.
14764 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
14765 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)
14766 Currently (July 2016), concepts are supported only in GCC 6.1.
14767 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
14768 If you use GCC 6.1, you can uncomment them.
14770 Template use rule summary:
14772 * [T.1: Use templates to raise the level of abstraction of code](#Rt-raise)
14773 * [T.2: Use templates to express algorithms that apply to many argument types](#Rt-algo)
14774 * [T.3: Use templates to express containers and ranges](#Rt-cont)
14775 * [T.4: Use templates to express syntax tree manipulation](#Rt-expr)
14776 * [T.5: Combine generic and OO techniques to amplify their strengths, not their costs](#Rt-generic-oo)
14778 Concept use rule summary:
14780 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
14781 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
14782 * [T.12: Prefer concept names over `auto` for local variables](#Rt-auto)
14783 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
14784 * ???
14786 Concept definition rule summary:
14788 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
14789 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
14790 * [T.22: Specify axioms for concepts](#Rt-axiom)
14791 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
14792 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
14793 * [T.25: Avoid complementary constraints](#Rt-not)
14794 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
14795 * [T.30: Use concept negation (`!C<T>`) sparingly to express a minor difference](#Rt-not)
14796 * [T.31: Use concept disjunction (`C1<T> || C2<T>`) sparingly to express alternatives](#Rt-or)
14797 * ???
14799 Template interface rule summary:
14801 * [T.40: Use function objects to pass operations to algorithms](#Rt-fo)
14802 * [T.41: Require only essential properties in a template's concepts](#Rt-essential)
14803 * [T.42: Use template aliases to simplify notation and hide implementation details](#Rt-alias)
14804 * [T.43: Prefer `using` over `typedef` for defining aliases](#Rt-using)
14805 * [T.44: Use function templates to deduce class template argument types (where feasible)](#Rt-deduce)
14806 * [T.46: Require template arguments to be at least `Regular` or `SemiRegular`](#Rt-regular)
14807 * [T.47: Avoid highly visible unconstrained templates with common names](#Rt-visible)
14808 * [T.48: If your compiler does not support concepts, fake them with `enable_if`](#Rt-concept-def)
14809 * [T.49: Where possible, avoid type-erasure](#Rt-erasure)
14811 Template definition rule summary:
14813 * [T.60: Minimize a template's context dependencies](#Rt-depend)
14814 * [T.61: Do not over-parameterize members (SCARY)](#Rt-scary)
14815 * [T.62: Place non-dependent class template members in a non-templated base class](#Rt-nondependent)
14816 * [T.64: Use specialization to provide alternative implementations of class templates](#Rt-specialization)
14817 * [T.65: Use tag dispatch to provide alternative implementations of functions](#Rt-tag-dispatch)
14818 * [T.67: Use specialization to provide alternative implementations for irregular types](#Rt-specialization2)
14819 * [T.68: Use `{}` rather than `()` within templates to avoid ambiguities](#Rt-cast)
14820 * [T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point](#Rt-customization)
14822 Template and hierarchy rule summary:
14824 * [T.80: Do not naively templatize a class hierarchy](#Rt-hier)
14825 * [T.81: Do not mix hierarchies and arrays](#Rt-array) // ??? somewhere in "hierarchies"
14826 * [T.82: Linearize a hierarchy when virtual functions are undesirable](#Rt-linear)
14827 * [T.83: Do not declare a member function template virtual](#Rt-virtual)
14828 * [T.84: Use a non-template core implementation to provide an ABI-stable interface](#Rt-abi)
14829 * [T.??: ????](#Rt-???)
14831 Variadic template rule summary:
14833 * [T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types](#Rt-variadic)
14834 * [T.101: ??? How to pass arguments to a variadic template ???](#Rt-variadic-pass)
14835 * [T.102: ??? How to process arguments to a variadic template ???](#Rt-variadic-process)
14836 * [T.103: Don't use variadic templates for homogeneous argument lists](#Rt-variadic-not)
14837 * [T.??: ????](#Rt-???)
14839 Metaprogramming rule summary:
14841 * [T.120: Use template metaprogramming only when you really need to](#Rt-metameta)
14842 * [T.121: Use template metaprogramming primarily to emulate concepts](#Rt-emulate)
14843 * [T.122: Use templates (usually template aliases) to compute types at compile time](#Rt-tmp)
14844 * [T.123: Use `constexpr` functions to compute values at compile time](#Rt-fct)
14845 * [T.124: Prefer to use standard-library TMP facilities](#Rt-std-tmp)
14846 * [T.125: If you need to go beyond the standard-library TMP facilities, use an existing library](#Rt-lib)
14847 * [T.??: ????](#Rt-???)
14849 Other template rules summary:
14851 * [T.140: Name all operations with potential for reuse](#Rt-name)
14852 * [T.141: Use an unnamed lambda if you need a simple function object in one place only](#Rt-lambda)
14853 * [T.142: Use template variables to simplify notation](#Rt-var)
14854 * [T.143: Don't write unintentionally nongeneric code](#Rt-nongeneric)
14855 * [T.144: Don't specialize function templates](#Rt-specialize-function)
14856 * [T.150: Check that a class matches a concept using `static_assert`](#Rt-check-class)
14857 * [T.??: ????](#Rt-???)
14859 ## <a name="SS-GP"></a>T.gp: Generic programming
14861 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
14863 ### <a name="Rt-raise"></a>T.1: Use templates to raise the level of abstraction of code
14865 ##### Reason
14867 Generality. Re-use. Efficiency. Encourages consistent definition of user types.
14869 ##### Example, bad
14871 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":
14873     template<typename T>
14874         // requires Incrementable<T>
14875     T sum1(vector<T>& v, T s)
14876     {
14877         for (auto x : v) s += x;
14878         return s;
14879     }
14881     template<typename T>
14882         // requires Simple_number<T>
14883     T sum2(vector<T>& v, T s)
14884     {
14885         for (auto x : v) s = s + x;
14886         return s;
14887     }
14889 Assuming that `Incrementable` does not support `+` and `Simple_number` does not support `+=`, we have overconstrained implementers of `sum1` and `sum2`.
14890 And, in this case, missed an opportunity for a generalization.
14892 ##### Example
14894     template<typename T>
14895         // requires Arithmetic<T>
14896     T sum(vector<T>& v, T s)
14897     {
14898         for (auto x : v) s += x;
14899         return s;
14900     }
14902 Assuming that `Arithmetic` requires both `+` and `+=`, we have constrained the user of `sum` to provide a complete arithmetic type.
14903 That is not a minimal requirement, but it gives the implementer of algorithms much needed freedom and ensures that any `Arithmetic` type
14904 can be used for a wide variety of algorithms.
14906 For additional generality and reusability, we could also use a more general `Container` or `Range` concept instead of committing to only one container, `vector`.
14908 ##### Note
14910 If we define a template to require exactly the operations required for a single implementation of a single algorithm
14911 (e.g., requiring just `+=` rather than also `=` and `+`) and only those, we have overconstrained maintainers.
14912 We aim to minimize requirements on template arguments, but the absolutely minimal requirements of an implementation is rarely a meaningful concept.
14914 ##### Note
14916 Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates)
14917 is to efficiently generalize operations/algorithms over a set of types with similar semantic properties.
14919 ##### Note
14921 The `requires` in the comments are uses of `concepts`.
14922 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
14923 Currently (July 2016), concepts are supported only in GCC 6.1.
14924 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
14925 If you use GCC 6.1, you can uncomment them.
14927 ##### Enforcement
14929 * Flag algorithms with "overly simple" requirements, such as direct use of specific operators without a concept.
14930 * Do not flag the definition of the "overly simple" concepts themselves; they may simply be building blocks for more useful concepts.
14932 ### <a name="Rt-algo"></a>T.2: Use templates to express algorithms that apply to many argument types
14934 ##### Reason
14936 Generality. Minimizing the amount of source code. Interoperability. Re-use.
14938 ##### Example
14940 That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range:
14942     template<typename Iter, typename Val>
14943         // requires Input_iterator<Iter>
14944         //       && Equality_comparable<Value_type<Iter>, Val>
14945     Iter find(Iter b, Iter e, Val v)
14946     {
14947         // ...
14948     }
14950 ##### Note
14952 Don't use a template unless you have a realistic need for more than one template argument type.
14953 Don't overabstract.
14955 ##### Enforcement
14957 ??? tough, probably needs a human
14959 ### <a name="Rt-cont"></a>T.3: Use templates to express containers and ranges
14961 ##### Reason
14963 Containers need an element type, and expressing that as a template argument is general, reusable, and type safe.
14964 It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it.
14966 ##### Example
14968     template<typename T>
14969         // requires Regular<T>
14970     class Vector {
14971         // ...
14972         T* elem;   // points to sz Ts
14973         int sz;
14974     };
14976     Vector<double> v(10);
14977     v[7] = 9.9;
14979 ##### Example, bad
14981     class Container {
14982         // ...
14983         void* elem;   // points to size elements of some type
14984         int sz;
14985     };
14987     Container c(10, sizeof(double));
14988     ((double*) c.elem)[] = 9.9;
14990 This doesn't directly express the intent of the programmer and hides the structure of the program from the type system and optimizer.
14992 Hiding the `void*` behind macros simply obscures the problems and introduces new opportunities for confusion.
14994 **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.
14995 See [Stable base](#Rt-abi).
14997 ##### Enforcement
14999 * Flag uses of `void*`s and casts outside low-level implementation code
15001 ### <a name="Rt-expr"></a>T.4: Use templates to express syntax tree manipulation
15003 ##### Reason
15005  ???
15007 ##### Example
15009     ???
15011 **Exceptions**: ???
15013 ### <a name="Rt-generic-oo"></a>T.5: Combine generic and OO techniques to amplify their strengths, not their costs
15015 ##### Reason
15017 Generic and OO techniques are complementary.
15019 ##### Example
15021 Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
15023     class Command {
15024         // pure virtual functions
15025     };
15027     // implementations
15028     template</*...*/>
15029     class ConcreteCommand : public Command {
15030         // implement virtuals
15031     };
15033 ##### Example
15035 Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout.
15036 Examples include type erasure as with `std::shared_ptr`'s deleter (but [don't overuse type erasure](#Rt-erasure)).
15038 ##### Note
15040 In a class template, nonvirtual functions are only instantiated if they're used -- but virtual functions are instantiated every time.
15041 This can bloat code size, and may overconstrain a generic type by instantiating functionality that is never needed.
15042 Avoid this, even though the standard-library facets made this mistake.
15044 ##### See also
15046 * ref ???
15047 * ref ???
15048 * ref ???
15050 ##### Enforcement
15052 See the reference to more specific rules.
15054 ## <a name="SS-concepts"></a>T.concepts: Concept rules
15056 Concepts is a facility for specifying requirements for template arguments.
15057 It is an [ISO technical specification](#Ref-conceptsTS), but currently supported only by GCC.
15058 Concepts are, however, crucial in the thinking about generic programming and the basis of much work on future C++ libraries
15059 (standard and other).
15061 This section assumes concept support
15063 Concept use rule summary:
15065 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
15066 * [T.11: Whenever possible use standard concepts](#Rt-std-concepts)
15067 * [T.12: Prefer concept names over `auto`](#Rt-auto)
15068 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
15069 * ???
15071 Concept definition rule summary:
15073 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
15074 * [T.21: Require a complete set of operations for a concept](#Rt-complete)
15075 * [T.22: Specify axioms for concepts](#Rt-axiom)
15076 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
15077 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
15078 * [T.25: Avoid complimentary constraints](#Rt-not)
15079 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
15080 * ???
15082 ## <a name="SS-concept-use"></a>T.con-use: Concept use
15084 ### <a name="Rt-concepts"></a>T.10: Specify concepts for all template arguments
15086 ##### Reason
15088 Correctness and readability.
15089 The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template.
15090 A concept dramatically improves documentation and error handling for the template.
15091 Specifying concepts for template arguments is a powerful design tool.
15093 ##### Example
15095     template<typename Iter, typename Val>
15096     //    requires Input_iterator<Iter>
15097     //             && Equality_comparable<Value_type<Iter>, Val>
15098     Iter find(Iter b, Iter e, Val v)
15099     {
15100         // ...
15101     }
15103 or equivalently and more succinctly:
15105     template<Input_iterator Iter, typename Val>
15106     //    requires Equality_comparable<Value_type<Iter>, Val>
15107     Iter find(Iter b, Iter e, Val v)
15108     {
15109         // ...
15110     }
15112 ##### Note
15114 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
15115 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)
15116 Currently (July 2016), concepts are supported only in GCC 6.1.
15117 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
15118 If you use GCC 6.1, you can uncomment them:
15120     template<typename Iter, typename Val>
15121         requires Input_iterator<Iter>
15122                && Equality_comparable<Value_type<Iter>, Val>
15123     Iter find(Iter b, Iter e, Val v)
15124     {
15125         // ...
15126     }
15128 ##### Note
15130 Plain `typename` (or `auto`) is the least constraining concept.
15131 It should be used only rarely when nothing more than "it's a type" can be assumed.
15132 This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking.
15134 **References**: TC++PL4, Palo Alto TR, Sutton
15136 ##### Enforcement
15138 Flag template type arguments without concepts
15140 ### <a name="Rt-std-concepts"></a>T.11: Whenever possible use standard concepts
15142 ##### Reason
15144  "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)
15145 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.
15147 ##### Note
15149 Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library.
15151 ##### Example (using TS concepts)
15153     template<typename T>
15154         // don't define this: Sortable is in the GSL
15155     concept Ordered_container = Sequence<T> && Random_access<Iterator<T>> && Ordered<Value_type<T>>;
15157     void sort(Ordered_container& s);
15159 This `Ordered_container` is quite plausible, but it is very similar to the `Sortable` concept in the GSL (and the Range TS).
15160 Is it better? Is it right? Does it accurately reflect the standard's requirements for `sort`?
15161 It is better and simpler just to use `Sortable`:
15163     void sort(Sortable& s);   // better
15165 ##### Note
15167 The set of "standard" concepts is evolving as we approach an ISO standard including concepts.
15169 ##### Note
15171 Designing a useful concept is challenging.
15173 ##### Enforcement
15175 Hard.
15177 * Look for unconstrained arguments, templates that use "unusual"/non-standard concepts, templates that use "homebrew" concepts without axioms.
15178 * Develop a concept-discovery tool (e.g., see [an early experiment](http://www.stroustrup.com/sle2010_webversion.pdf)).
15180 ### <a name="Rt-auto"></a>T.12: Prefer concept names over `auto` for local variables
15182 ##### Reason
15184  `auto` is the weakest concept. Concept names convey more meaning than just `auto`.
15186 ##### Example (using TS concepts)
15188     vector<string> v;
15189     auto& x = v.front();     // bad
15190     String& s = v.begin();   // good (String is a GSL concept)
15192 ##### Enforcement
15194 * ???
15196 ### <a name="Rt-shorthand"></a>T.13: Prefer the shorthand notation for simple, single-type argument concepts
15198 ##### Reason
15200 Readability. Direct expression of an idea.
15202 ##### Example (using TS concepts)
15204 To say "`T` is `Sortable`":
15206     template<typename T>       // Correct but verbose: "The parameter is
15207     //    requires Sortable<T>   // of type T which is the name of a type
15208     void sort(T&);             // that is Sortable"
15210     template<Sortable T>       // Better (assuming support for concepts): "The parameter is of type T
15211     void sort(T&);             // which is Sortable"
15213     void sort(Sortable&);      // Best (assuming support for concepts): "The parameter is Sortable"
15215 The shorter versions better match the way we speak. Note that many templates don't need to use the `template` keyword.
15217 ##### Note
15219 "Concepts" are defined in an ISO Technical specification: [concepts](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
15220 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)
15221 Currently (July 2016), concepts are supported only in GCC 6.1.
15222 Consequently, we comment out uses of concepts in examples; that is, we use them as formalized comments only.
15223 If you use a compiler that supports concepts (e.g., GCC 6.1), you can remove the `//`.
15225 ##### Enforcement
15227 * Not feasible in the short term when people convert from the `<typename T>` and `<class T`> notation.
15228 * Later, flag declarations that first introduces a typename and then constrains it with a simple, single-type-argument concept.
15230 ## <a name="SS-concepts-def"></a>T.concepts.def: Concept definition rules
15232 Defining good concepts is non-trivial.
15233 Concepts are meant to represent fundamental concepts in an application domain (hence the name "concepts").
15234 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
15235 and will not give the full benefits of the mechanism.
15237 Obviously, defining concepts will be most useful for code that can use an implementation (e.g., GCC 6.1),
15238 but defining concepts is in itself a useful design technique and help catch conceptual errors and clean up the concepts (sic!) of an implementation.
15240 ### <a name="Rt-low"></a>T.20: Avoid "concepts" without meaningful semantics
15242 ##### Reason
15244 Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered."
15245 Simple constraints, such as "has a `+` operator" and "has a `>` operator" cannot be meaningfully specified in isolation
15246 and should be used only as building blocks for meaningful concepts, rather than in user code.
15248 ##### Example, bad (using TS concepts)
15250     template<typename T>
15251     concept Addable = has_plus<T>;    // bad; insufficient
15253     template<Addable N> auto algo(const N& a, const N& b) // use two numbers
15254     {
15255         // ...
15256         return a + b;
15257     }
15259     int x = 7;
15260     int y = 9;
15261     auto z = plus(x, y);   // z = 16
15263     string xx = "7";
15264     string yy = "9";
15265     auto zz = plus(xx, yy);   // zz = "79"
15267 Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types.
15268 This `Addable` violates the mathematical rule that addition is supposed to be commutative: `a+b == b+a`.
15270 ##### Note
15272 The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint.
15274 ##### Example (using TS concepts)
15276     template<typename T>
15277     // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
15278     concept Number = has_plus<T>
15279                      && has_minus<T>
15280                      && has_multiply<T>
15281                      && has_divide<T>;
15283     template<Number N> auto algo(const N& a, const N& b) // use two numbers
15284     {
15285         // ...
15286         return a + b;
15287     }
15289     int x = 7;
15290     int y = 9;
15291     auto z = plus(x, y);   // z = 18
15293     string xx = "7";
15294     string yy = "9";
15295     auto zz = plus(xx, yy);   // error: string is not a Number
15297 ##### Note
15299 Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.
15301 ##### Enforcement
15303 * Flag single-operation `concepts` when used outside the definition of other `concepts`.
15304 * Flag uses of `enable_if` that appears to simulate single-operation `concepts`.
15307 ### <a name="RT-operations"></a>T.21: Require a complete set of operations for a concept
15309 ##### Reason
15311 Ease of comprehension.
15312 Improved interoperability.
15313 Helps implementers and maintainers.
15315 ##### Note
15317 This is a specific variant of the general rule that [a concept must make semantic sense](#Rt-low).
15319 ##### Example, bad (using TS concepts)
15321     template<typename T> concept Subtractable = requires(T a, T, b) { a-b; };
15323 This makes no semantic sense.
15324 You need at least `+` to make `-` meaningful and useful.
15326 Examples of complete sets are
15328 * `Arithmetic`: `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`
15329 * `Comparable`: `<`, `>`, `<=`, `>=`, `==`, `!=`
15331 ##### Note
15333 This rule applies whether we use direct language support for concepts or not.
15334 It is a general design rule that even applies to non-templates:
15336     class Minimal {
15337         // ...
15338     };
15340     bool operator==(const Minimal&, const Minimal&);
15341     bool operator<(const Minimal&, const Minimal&);
15343     Minimal operator+(const Minimal&, const Minimal&);
15344     // no other operators
15346     void f(const Minimal& x, const Minimal& y)
15347     {
15348         if (!(x == y) { /* ... */ }     // OK
15349         if (x != y) { /* ... */ }       // surprise! error
15351         while (!(x < y)) { /* ... */ }  // OK
15352         while (x >= y) { /* ... */ }    // surprise! error
15354         x = x + y;        // OK
15355         x += y;             // surprise! error
15356     }
15358 This is minimal, but surprising and constraining for users.
15359 It could even be less efficient.
15361 The rule supports the view that a concept should reflect a (mathematically) coherent set of operations.
15363 ##### Example
15365     class Convenient {
15366         // ...
15367     };
15369     bool operator==(const Convenient&, const Convenient&);
15370     bool operator<(const Convenient&, const Convenient&);
15371     // ... and the other comparison operators ...
15373     Minimal operator+(const Convenient&, const Convenient&);
15374     // .. and the other arithmetic operators ...
15376     void f(const Convenient& x, const Convenient& y)
15377     {
15378         if (!(x == y) { /* ... */ }     // OK
15379         if (x != y) { /* ... */ }       // OK
15381         while (!(x < y)) { /* ... */ }  // OK
15382         while (x >= y) { /* ... */ }    // OK
15384         x = x + y;     // OK
15385         x += y;      // OK
15386     }
15388 It can be a nuisance to define all operators, but not hard.
15389 Ideally, that rule should be language supported by giving you comparison operators by default.
15391 ##### Enforcement
15393 * Flag classes the support "odd" subsets of a set of operators, e.g., `==` but not `!=` or `+` but not `-`.
15394   Yes, `std::string` is "odd", but it's too late to change that.
15397 ### <a name="Rt-axiom"></a>T.22: Specify axioms for concepts
15399 ##### Reason
15401 A meaningful/useful concept has a semantic meaning.
15402 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.
15403 Specifying semantics is a powerful design tool.
15405 ##### Example (using TS concepts)
15407     template<typename T>
15408         // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
15409         // axiom(T a, T b) { a + b == b + a; a - a == 0; a * (b + c) == a * b + a * c; /*...*/ }
15410         concept Number = requires(T a, T b) {
15411             {a + b} -> T;   // the result of a + b is convertible to T
15412             {a - b} -> T;
15413             {a * b} -> T;
15414             {a / b} -> T;
15415         }
15417 ##### Note
15419 This is an axiom in the mathematical sense: something that may be assumed without proof.
15420 In general, axioms are not provable, and when they are the proof is often beyond the capability of a compiler.
15421 An axiom may not be general, but the template writer may assume that it holds for all inputs actually used (similar to a precondition).
15423 ##### Note
15425 In this context axioms are Boolean expressions.
15426 See the [Palo Alto TR](#S-references) for examples.
15427 Currently, C++ does not support axioms (even the ISO Concepts TS), so we have to make do with comments for a longish while.
15428 Once language support is available, the `//` in front of the axiom can be removed
15430 ##### Note
15432 The GSL concepts have well defined semantics; see the Palo Alto TR and the Ranges TS.
15434 ##### Exception (using TS concepts)
15436 Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics.
15437 Finding good semantics can take effort and time.
15438 An incomplete set of constraints can still be very useful:
15440     // balancer for a generic binary tree
15441     template<typename Node> concept bool Balancer = requires(Node* p) {
15442         add_fixup(p);
15443         touch(p);
15444         detach(p);
15445     }
15447 So a `Balancer` must supply at least thee operations on a tree `Node`,
15448 but we are not yet ready to specify detailed semantics because a new kind of balanced tree might require more operations
15449 and the precise general semantics for all nodes is hard to pin down in the early stages of design.
15451 A "concept" that is incomplete or without a well-specified semantics can still be useful.
15452 For example, it allows for some checking during initial experimentation.
15453 However, it should not be assumed to be stable.
15454 Each new use case may require such an incomplete concepts to be improved.
15456 ##### Enforcement
15458 * Look for the word "axiom" in concept definition comments
15460 ### <a name="Rt-refine"></a>T.23: Differentiate a refined concept from its more general case by adding new use patterns.
15462 ##### Reason
15464 Otherwise they cannot be distinguished automatically by the compiler.
15466 ##### Example (using TS concepts)
15468     template<typename I>
15469     concept bool Input_iter = requires(I iter) { ++iter; };
15471     template<typename I>
15472     concept bool Fwd_iter = Input_iter<I> && requires(I iter) { iter++; }
15474 The compiler can determine refinement based on the sets of required operations (here, suffix `++`).
15475 This decreases the burden on implementers of these types since
15476 they do not need any special declarations to "hook into the concept".
15477 If two concepts have exactly the same requirements, they are logically equivalent (there is no refinement).
15479 ##### Enforcement
15481 * Flag a concept that has exactly the same requirements as another already-seen concept (neither is more refined).
15482 To disambiguate them, see [T.24](#Rt-tag).
15484 ### <a name="Rt-tag"></a>T.24: Use tag classes or traits to differentiate concepts that differ only in semantics.
15486 ##### Reason
15488 Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them.
15490 ##### Example (using TS concepts)
15492     template<typename I>    // iterator providing random access
15493     concept bool RA_iter = ...;
15495     template<typename I>    // iterator providing random access to contiguous data
15496     concept bool Contiguous_iter =
15497         RA_iter<I> && is_contiguous<I>::value;  // using is_contiguous trait
15499 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
15501 Wrapping a tag class into a concept leads to a simpler expression of this idea:
15503     template<typename I> concept Contiguous = is_contiguous<I>::value;
15505     template<typename I>
15506     concept bool Contiguous_iter = RA_iter<I> && Contiguous<I>;
15508 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
15510 ##### Note
15512 Traits can be trait classes or type traits.
15513 These can be user-defined or standard-library ones.
15514 Prefer the standard-library ones.
15516 ##### Enforcement
15518 * The compiler flags ambiguous use of identical concepts.
15519 * Flag the definition of identical concepts.
15521 ### <a name="Rt-not"></a>T.25: Avoid complementary constraints
15523 ##### Reason
15525 Clarity. Maintainability.
15526 Functions with complementary requirements expressed using negation are brittle.
15528 ##### Example (using TS concepts)
15530 Initially, people will try to define functions with complementary requirements:
15532     template<typename T>
15533         requires !C<T>    // bad
15534     void f();
15536     template<typename T>
15537         requires C<T>
15538     void f();
15540 This is better:
15542     template<typename T>   // general template
15543         void f();
15545     template<typename T>   // specialization by concept
15546         requires C<T>
15547     void f();
15549 The compiler will choose the unconstrained template only when `C<T>` is
15550 unsatisfied. If you do not want to (or cannot) define an unconstrained
15551 version of `f()`, then delete it.
15553     template<typename T>
15554     void f() = delete;
15556 The compiler will select the overload and emit an appropriate error.
15558 ##### Note
15560 Complementary constraints are unfortunately common in `enable_if` code:
15562     template<typename T>
15563     enable_if<!C<T>, void>   // bad
15564     f();
15566     template<typename T>
15567     enable_if<C<T>, void>
15568     f();
15571 ##### Note
15573 Complementary requirements on one requirements is sometimes (wrongly) considered manageable.
15574 However, for two or more requirements the number of definitions needs can go up exponentially (2,4,9,16,...):
15576     C1<T> && C2<T>
15577     !C1<T> && C2<T>
15578     C1<T> && !C2<T>
15579     !C1<T> && !C2<T>
15581 Now the opportunities for errors multiply.
15583 ##### Enforcement
15585 * Flag pairs of functions with `C<T>` and `!C<T>` constraints
15587 ### <a name="Rt-use"></a>T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax
15589 ##### Reason
15591 The definition is more readable and corresponds directly to what a user has to write.
15592 Conversions are taken into account. You don't have to remember the names of all the type traits.
15594 ##### Example (using TS concepts)
15596 You might be tempted to define a concept `Equality` like this:
15598     template<typename T> concept Equality = has_equal<T> && has_not_equal<T>;
15600 Obviously, it would be better and easier just to use the standard `EqualityComparable`,
15601 but - just as an example - if you had to define such a concept, prefer:
15603     template<typename T> concept Equality = requires(T a, T b) {
15604         bool == { a == b }
15605         bool == { a != b }
15606         // axiom { !(a == b) == (a != b) }
15607         // axiom { a = b; => a == b }  // => means "implies"
15608     }
15610 as opposed to defining two meaningless concepts `has_equal` and `has_not_equal` just as helpers in the definition of `Equality`.
15611 By "meaningless" we mean that we cannot specify the semantics of `has_equal` in isolation.
15613 ##### Enforcement
15617 ## <a name="SS-temp-interface"></a>Template interfaces
15619 Over the years, programming with templates have suffered from a weak distinction between the interface of a template
15620 and its implementation.
15621 Before concepts, that distinction had no direct language support.
15622 However, the interface to a template is a critical concept - a contract between a user and an implementer - and should be carefully designed.
15624 ### <a name="Rt-fo"></a>T.40: Use function objects to pass operations to algorithms
15626 ##### Reason
15628 Function objects can carry more information through an interface than a "plain" pointer to function.
15629 In general, passing function objects gives better performance than passing pointers to functions.
15631 ##### Example (using TS concepts)
15633     bool greater(double x, double y) { return x > y; }
15634     sort(v, greater);                                    // pointer to function: potentially slow
15635     sort(v, [](double x, double y) { return x > y; });   // function object
15636     sort(v, std::greater<>);                             // function object
15638     bool greater_than_7(double x) { return x > 7; }
15639     auto x = find_if(v, greater_than_7);                 // pointer to function: inflexible
15640     auto y = find_if(v, [](double x) { return x > 7; }); // function object: carries the needed data
15641     auto z = find_if(v, Greater_than<double>(7));        // function object: carries the needed data
15643 You can, of course, generalize those functions using `auto` or (when and where available) concepts. For example:
15645     auto y1 = find_if(v, [](Ordered x) { return x > 7; }); // require an ordered type
15646     auto z1 = find_if(v, [](auto x) { return x > 7; });    // hope that the type has a >
15648 ##### Note
15650 Lambdas generate function objects.
15652 ##### Note
15654 The performance argument depends on compiler and optimizer technology.
15656 ##### Enforcement
15658 * Flag pointer to function template arguments.
15659 * Flag pointers to functions passed as arguments to a template (risk of false positives).
15662 ### <a name="Rt-essential"></a>T.41: Require only essential properties in a template's concepts
15664 ##### Reason
15666 Keep interfaces simple and stable.
15668 ##### Example (using TS concepts)
15670 Consider, a `sort` instrumented with (oversimplified) simple debug support:
15672     void sort(Sortable& s)  // sort sequence s
15673     {
15674         if (debug) cerr << "enter sort( " << s <<  ")\n";
15675         // ...
15676         if (debug) cerr << "exit sort( " << s <<  ")\n";
15677     }
15679 Should this be rewritten to:
15681     template<Sortable S>
15682         requires Streamable<S>
15683     void sort(S& s)  // sort sequence s
15684     {
15685         if (debug) cerr << "enter sort( " << s <<  ")\n";
15686         // ...
15687         if (debug) cerr << "exit sort( " << s <<  ")\n";
15688     }
15690 After all, there is nothing in `Sortable` that requires `iostream` support.
15691 On the other hand, there is nothing in the fundamental idea of sorting that says anything about debugging.
15693 ##### Note
15695 If we require every operation used to be listed among the requirements, the interface becomes unstable:
15696 Every time we change the debug facilities, the usage data gathering, testing support, error reporting, etc.
15697 The definition of the template would need change and every use of the template would have to be recompiled.
15698 This is cumbersome, and in some environments infeasible.
15700 Conversely, if we use an operation in the implementation that is not guaranteed by concept checking,
15701 we may get a late compile-time error.
15703 By not using concept checking for properties of a template argument that is not considered essential,
15704 we delay checking until instantiation time.
15705 We consider this a worthwhile tradeoff.
15707 Note that using non-local, non-dependent names (such as `debug` and `cerr`) also introduces context dependencies that may lead to "mysterious" errors.
15709 ##### Note
15711 It can be hard to decide which properties of a type is essential and which are not.
15713 ##### Enforcement
15717 ### <a name="Rt-alias"></a>T.42: Use template aliases to simplify notation and hide implementation details
15719 ##### Reason
15721 Improved readability.
15722 Implementation hiding.
15723 Note that template aliases replace many uses of traits to compute a type.
15724 They can also be used to wrap a trait.
15726 ##### Example
15728     template<typename T, size_t N>
15729     class Matrix {
15730         // ...
15731         using Iterator = typename std::vector<T>::iterator;
15732         // ...
15733     };
15735 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>::`.
15737 ##### Example
15739     template<typename T>
15740     void user(T& c)
15741     {
15742         // ...
15743         typename container_traits<T>::value_type x; // bad, verbose
15744         // ...
15745     }
15747     template<typename T>
15748     using Value_type = typename container_traits<T>::value_type;
15751 This saves the user of `Value_type` from having to know the technique used to implement `value_type`s.
15753     template<typename T>
15754     void user2(T& c)
15755     {
15756         // ...
15757         Value_type<T> x;
15758         // ...
15759     }
15761 ##### Note
15763 A simple, common use could be expressed: "Wrap traits!"
15765 ##### Enforcement
15767 * Flag use of `typename` as a disambiguator outside `using` declarations.
15768 * ???
15770 ### <a name="Rt-using"></a>T.43: Prefer `using` over `typedef` for defining aliases
15772 ##### Reason
15774 Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration.
15775 Generality: `using` can be used for template aliases, whereas `typedef`s can't easily be templates.
15776 Uniformity: `using` is syntactically similar to `auto`.
15778 ##### Example
15780     typedef int (*PFI)(int);   // OK, but convoluted
15782     using PFI2 = int (*)(int);   // OK, preferred
15784     template<typename T>
15785     typedef int (*PFT)(T);      // error
15787     template<typename T>
15788     using PFT2 = int (*)(T);   // OK
15790 ##### Enforcement
15792 * Flag uses of `typedef`. This will give a lot of "hits" :-(
15794 ### <a name="Rt-deduce"></a>T.44: Use function templates to deduce class template argument types (where feasible)
15796 ##### Reason
15798 Writing the template argument types explicitly can be tedious and unnecessarily verbose.
15800 ##### Example
15802     tuple<int, string, double> t1 = {1, "Hamlet", 3.14};   // explicit type
15803     auto t2 = make_tuple(1, "Ophelia"s, 3.14);         // better; deduced type
15805 Note the use of the `s` suffix to ensure that the string is a `std::string`, rather than a C-style string.
15807 ##### Note
15809 Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions may become redundant in the future.
15811 ##### Exception
15813 Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly:
15815     vector<double> v = { 1, 2, 3, 7.9, 15.99 };
15816     list<Record*> lst;
15818 ##### Note
15820 Note that C++17 will make this rule redundant by allowing the template arguments to be deduced directly from constructor arguments:
15821 [Template parameter deduction for constructors (Rev. 3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r1.html).
15822 For example:
15824     tuple t1 = {1, "Hamlet"s, 3.14}; // deduced: tuple<int, string, double>
15826 ##### Enforcement
15828 Flag uses where an explicitly specialized type exactly matches the types of the arguments used.
15830 ### <a name="Rt-regular"></a>T.46: Require template arguments to be at least `Regular` or `SemiRegular`
15832 ##### Reason
15834  Readability.
15835  Preventing surprises and errors.
15836  Most uses support that anyway.
15838 ##### Example
15840     class X {
15841             // ...
15842     public:
15843         explicit X(int);
15844         X(const X&);            // copy
15845         X operator=(const X&);
15846         X(X&&);                 // move
15847         X& operator=(X&&);
15848         ~X();
15849         // ... no more constructors ...
15850     };
15852     X x {1};    // fine
15853     X y = x;      // fine
15854     std::vector<X> v(10); // error: no default constructor
15856 ##### Note
15858 Semiregular requires default constructible.
15860 ##### Enforcement
15862 * Flag types that are not at least `SemiRegular`.
15864 ### <a name="Rt-visible"></a>T.47: Avoid highly visible unconstrained templates with common names
15866 ##### Reason
15868  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.
15869  This is particularly annoying/dangerous when ADL is used.
15870  Common names make this problem more likely.
15872 ##### Example
15874     namespace Bad {
15875         struct S { int m; };
15876         template<typename T1, typename T2>
15877         bool operator==(T1, T2) { cout << "Bad\n"; return true; }
15878     }
15880     namespace T0 {
15881         bool operator==(int, Bad::S) { cout << "T0\n"; return true; }  // compare to int
15883         void test()
15884         {
15885             Bad::S bad{ 1 };
15886             vector<int> v(10);
15887             bool b = 1 == bad;
15888             bool b2 = v.size() == bad;
15889         }
15890     }
15892 This prints `T0` and `Bad`.
15894 Now the `==` in `Bad` was designed to cause trouble, but would you have spotted the problem in real code?
15895 The problem is that `v.size()` returns an `unsigned` integer so that a conversion is needed to call the local `==`;
15896 the `==` in `Bad` requires no conversions.
15897 Realistic types, such as the standard library iterators can be made to exhibit similar anti-social tendencies.
15899 ##### Note
15901 If an unconstrained template is defined in the same namespace as a type,
15902 that unconstrained template can be found by ADL (as happened in the example).
15903 That is, it is highly visible.
15905 ##### Note
15907 This rule should not be necessary, but the committee cannot agree to exclude unconstrained templated from ADL.
15909 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`.
15912 ##### Enforcement
15914 Flag templates defined in a namespace where concrete types are also defined (maybe not feasible until we have concepts).
15917 ### <a name="Rt-concept-def"></a>T.48: If your compiler does not support concepts, fake them with `enable_if`
15919 ##### Reason
15921 Because that's the best we can do without direct concept support.
15922 `enable_if` can be used to conditionally define functions and to select among a set of functions.
15924 ##### Example
15926     enable_if<???>
15928 ##### Note
15930 Beware of [complementary constraints](# T.25).
15931 Faking concept overloading using `enable_if` sometimes forces us to use that error-prone design technique.
15933 ##### Enforcement
15937 ### <a name="Rt-erasure"></a>T.49: Where possible, avoid type-erasure
15939 ##### Reason
15941 Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary.
15943 ##### Example
15945     ???
15947 **Exceptions**: Type erasure is sometimes appropriate, such as for `std::function`.
15949 ##### Enforcement
15954 ##### Note
15957 ## <a name="SS-temp-def"></a>T.def: Template definitions
15959 A template definition (class or function) can contain arbitrary code, so only a comprehensive review of C++ programming techniques would cover this topic.
15960 However, this section focuses on what is specific to template implementation.
15961 In particular, it focuses on a template definition's dependence on its context.
15963 ### <a name="Rt-depend"></a>T.60: Minimize a template's context dependencies
15965 ##### Reason
15967 Eases understanding.
15968 Minimizes errors from unexpected dependencies.
15969 Eases tool creation.
15971 ##### Example
15973     template<typename C>
15974     void sort(C& c)
15975     {
15976         std::sort(begin(c), end(c)); // necessary and useful dependency
15977     }
15979     template<typename Iter>
15980     Iter algo(Iter first, Iter last) {
15981         for (; first != last; ++first) {
15982             auto x = sqrt(*first); // potentially surprising dependency: which sqrt()?
15983             helper(first, x);      // potentially surprising dependency:
15984                                    // helper is chosen based on first and x
15985             TT var = 7;            // potentially surprising dependency: which TT?
15986         }
15987     }
15989 ##### Note
15991 Templates typically appear in header files so their context dependencies are more vulnerable to `#include` order dependencies than functions in `.cpp` files.
15993 ##### Note
15995 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.
15996 For example, an algorithm usually uses other algorithms and invoke operations that does not exclusively operate on arguments.
15997 And don't get us started on macros!
15998 See also [T.69](#Rt-customization)
16000 ##### Enforcement
16002 ??? Tricky
16004 ### <a name="Rt-scary"></a>T.61: Do not over-parameterize members (SCARY)
16006 ##### Reason
16008 A member that does not depend on a template parameter cannot be used except for a specific template argument.
16009 This limits use and typically increases code size.
16011 ##### Example, bad
16013     template<typename T, typename A = std::allocator{}>
16014         // requires Regular<T> && Allocator<A>
16015     class List {
16016     public:
16017         struct Link {   // does not depend on A
16018             T elem;
16019             T* pre;
16020             T* suc;
16021         };
16023         using iterator = Link*;
16025         iterator first() const { return head; }
16027         // ...
16028     private:
16029         Link* head;
16030     };
16032     List<int> lst1;
16033     List<int, My_allocator> lst2;
16035     ???
16037 This looks innocent enough, but ???
16039     template<typename T>
16040     struct Link {
16041         T elem;
16042         T* pre;
16043         T* suc;
16044     };
16046     template<typename T, typename A = std::allocator{}>
16047         // requires Regular<T> && Allocator<A>
16048     class List2 {
16049     public:
16050         using iterator = Link<T>*;
16052         iterator first() const { return head; }
16054         // ...
16055     private:
16056         Link* head;
16057     };
16059     List<int> lst1;
16060     List<int, My_allocator> lst2;
16062     ???
16064 ##### Enforcement
16066 * Flag member types that do not depend on every template argument
16067 * Flag member functions that do not depend on every template argument
16069 ### <a name="Rt-nondependent"></a>T.62: Place non-dependent class template members in a non-templated base class
16071 ##### Reason
16073  Allow the base class members to be used without specifying template arguments and without template instantiation.
16075 ##### Example
16077     template<typename T>
16078     class Foo {
16079     public:
16080         enum { v1, v2 };
16081         // ...
16082     };
16086     struct Foo_base {
16087         enum { v1, v2 };
16088         // ...
16089     };
16091     template<typename T>
16092     class Foo : public Foo_base {
16093     public:
16094         // ...
16095     };
16097 ##### Note
16099 A more general version of this rule would be
16100 "If a template class member depends on only N template parameters out of M, place it in a base class with only N parameters."
16101 For N == 1, we have a choice of a base class of a class in the surrounding scope as in [T.61](#Rt-scary).
16103 ??? What about constants? class statics?
16105 ##### Enforcement
16107 * Flag ???
16109 ### <a name="Rt-specialization"></a>T.64: Use specialization to provide alternative implementations of class templates
16111 ##### Reason
16113 A template defines a general interface.
16114 Specialization offers a powerful mechanism for providing alternative implementations of that interface.
16116 ##### Example
16118     ??? string specialization (==)
16120     ??? representation specialization ?
16122 ##### Note
16126 ##### Enforcement
16130 ### <a name="Rt-tag-dispatch"></a>T.65: Use tag dispatch to provide alternative implementations of a function
16132 ##### Reason
16134 * A template defines a general interface.
16135 * Tag dispatch allows us to select implementations based on specific properties of an argument type.
16136 * Performance.
16138 ##### Example
16140 This is a simplified version of `std::copy` (ignoring the possibility of non-contiguous sequences)
16142     struct pod_tag {};
16143     struct non_pod_tag {};
16145     template<class T> struct copy_trait { using tag = non_pod_tag; };   // T is not "plain old data"
16147     template<> struct copy_trait<int> { using tag = pod_tag; };         // int is "plain old data"
16149     template<class Iter>
16150     Out copy_helper(Iter first, Iter last, Iter out, pod_tag)
16151     {
16152         // use memmove
16153     }
16155     template<class Iter>
16156     Out copy_helper(Iter first, Iter last, Iter out, non_pod_tag)
16157     {
16158         // use loop calling copy constructors
16159     }
16161     template<class Itert>
16162     Out copy(Iter first, Iter last, Iter out)
16163     {
16164         return copy_helper(first, last, out, typename copy_trait<Iter>::tag{})
16165     }
16167     void use(vector<int>& vi, vector<int>& vi2, vector<string>& vs, vector<string>& vs2)
16168     {
16169         copy(vi.begin(), vi.end(), vi2.begin()); // uses memmove
16170         copy(vs.begin(), vs.end(), vs2.begin()); // uses a loop calling copy constructors
16171     }
16173 This is a general and powerful technique for compile-time algorithm selection.
16175 ##### Note
16177 When `concept`s become widely available such alternatives can be distinguished directly:
16179     template<class Iter>
16180         requires Pod<Value_type<iter>>
16181     Out copy_helper(In, first, In last, Out out)
16182     {
16183         // use memmove
16184     }
16186     template<class Iter>
16187     Out copy_helper(In, first, In last, Out out)
16188     {
16189         // use loop calling copy constructors
16190     }
16192 ##### Enforcement
16197 ### <a name="Rt-specialization2"></a>T.67: Use specialization to provide alternative implementations for irregular types
16199 ##### Reason
16201  ???
16203 ##### Example
16205     ???
16207 ##### Enforcement
16211 ### <a name="Rt-cast"></a>T.68: Use `{}` rather than `()` within templates to avoid ambiguities
16213 ##### Reason
16215  `()` is vulnerable to grammar ambiguities.
16217 ##### Example
16219     template<typename T, typename U>
16220     void f(T t, U u)
16221     {
16222         T v1(x);    // is v1 a function of a variable?
16223         T v2 {x};   // variable
16224         auto x = T(u);  // construction or cast?
16225     }
16227     f(1, "asdf"); // bad: cast from const char* to int
16229 ##### Enforcement
16231 * flag `()` initializers
16232 * flag function-style casts
16235 ### <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
16237 ##### Reason
16239 * Provide only intended flexibility.
16240 * Avoid vulnerability to accidental environmental changes.
16242 ##### Example
16244 There are three major ways to let calling code customize a template.
16246     template<class T>
16247         // Call a member function
16248     void test1(T t)
16249     {
16250         t.f();    // require T to provide f()
16251     }
16253     template<class T>
16254     void test2(T t)
16255         // Call a nonmember function without qualification
16256     {
16257         f(t);  // require f(/*T*/) be available in caller's scope or in T's namespace
16258     }
16260     template<class T>
16261     void test3(T t)
16262         // Invoke a "trait"
16263     {
16264         test_traits<T>::f(t); // require customizing test_traits<>
16265                               // to get non-default functions/types
16266     }
16268 A trait is usually a type alias to compute a type,
16269 a `constexpr` function to compute a value,
16270 or a traditional traits template to be specialized on the user's type.
16272 ##### Note
16274 If you intend to call your own helper function `helper(t)` with a value `t` that depends on a template type parameter,
16275 put it in a `::detail` namespace and qualify the call as `detail::helper(t);`.
16276 An unqualified call becomes a customization point where any function `helper` in the namespace of `t`'s type can be invoked;
16277 this can cause problems like [unintentionally invoking unconstrained function templates](#Rt-unconstrained-adl).
16280 ##### Enforcement
16282 * 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.
16285 ## <a name="SS-temp-hier"></a>T.temp-hier: Template and hierarchy rules:
16287 Templates are the backbone of C++'s support for generic programming and class hierarchies the backbone of its support
16288 for object-oriented programming.
16289 The two language mechanisms can be used effectively in combination, but a few design pitfalls must be avoided.
16291 ### <a name="Rt-hier"></a>T.80: Do not naively templatize a class hierarchy
16293 ##### Reason
16295 Templating a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.
16297 ##### Example, bad
16299     template<typename T>
16300     struct Container {         // an interface
16301         virtual T* get(int i);
16302         virtual T* first();
16303         virtual T* next();
16304         virtual void sort();
16305     };
16307     template<typename T>
16308     class Vector : public Container<T> {
16309     public:
16310         // ...
16311     };
16313     vector<int> vi;
16314     vector<string> vs;
16316 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.
16318 Given this, the compiler cannot know if `vector<int>::sort()` is called, so it must generate code for it.
16319 Similar for `vector<string>::sort()`.
16320 Unless those two functions are called that's code bloat.
16321 Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.
16323 ##### Note
16325 In many cases you can provide a stable interface by not parameterizing a base;
16326 see ["stable base"](#Rt-abi) and [OO and GP](#Rt-generic-oo)
16328 ##### Enforcement
16330 * Flag virtual functions that depend on a template argument. ??? False positives
16332 ### <a name="Rt-array"></a>T.81: Do not mix hierarchies and arrays
16334 ##### Reason
16336 An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.
16338 ##### Example
16340 Assume that `Apple` and `Pear` are two kinds of `Fruit`s.
16342     void maul(Fruit* p)
16343     {
16344         *p = Pear{};     // put a Pear into *p
16345         p[1] = Pear{};   // put a Pear into p[2]
16346     }
16348     Apple aa [] = { an_apple, another_apple };   // aa contains Apples (obviously!)
16350     maul(aa);
16351     Apple& a0 = &aa[0];   // a Pear?
16352     Apple& a1 = &aa[1];   // a Pear?
16354 Probably, `aa[0]` will be a `Pear` (without the use of a cast!).
16355 If `sizeof(Apple) != sizeof(Pear)` the access to `aa[1]` will not be aligned to the proper start of an object in the array.
16356 We have a type violation and possibly (probably) a memory corruption.
16357 Never write such code.
16359 Note that `maul()` violates the a `T*` points to an individual object [Rule](#???).
16361 **Alternative**: Use a proper (templatized) container:
16363     void maul2(Fruit* p)
16364     {
16365         *p = Pear{};   // put a Pear into *p
16366     }
16368     vector<Apple> va = { an_apple, another_apple };   // va contains Apples (obviously!)
16370     maul2(va);       // error: cannot convert a vector<Apple> to a Fruit*
16371     maul2(&va[0]);   // you asked for it
16373     Apple& a0 = &va[0];   // a Pear?
16375 Note that the assignment in `maul2()` violated the no-slicing [Rule](#???).
16377 ##### Enforcement
16379 * Detect this horror!
16381 ### <a name="Rt-linear"></a>T.82: Linearize a hierarchy when virtual functions are undesirable
16383 ##### Reason
16385  ???
16387 ##### Example
16389     ???
16391 ##### Enforcement
16395 ### <a name="Rt-virtual"></a>T.83: Do not declare a member function template virtual
16397 ##### Reason
16399 C++ does not support that.
16400 If it did, vtbls could not be generated until link time.
16401 And in general, implementations must deal with dynamic linking.
16403 ##### Example, don't
16405     class Shape {
16406         // ...
16407         template<class T>
16408         virtual bool intersect(T* p);   // error: template cannot be virtual
16409     };
16411 ##### Note
16413 We need a rule because people keep asking about this
16415 ##### Alternative
16417 Double dispatch, visitors, calculate which function to call
16419 ##### Enforcement
16421 The compiler handles that.
16423 ### <a name="Rt-abi"></a>T.84: Use a non-template core implementation to provide an ABI-stable interface
16425 ##### Reason
16427 Improve stability of code.
16428 Avoid code bloat.
16430 ##### Example
16432 It could be a base class:
16434     struct Link_base {   // stable
16435         Link_base* suc;
16436         Link_base* pre;
16437     };
16439     template<typename T>   // templated wrapper to add type safety
16440     struct Link : Link_base {
16441         T val;
16442     };
16444     struct List_base {
16445         Link_base* first;   // first element (if any)
16446         int sz;             // number of elements
16447         void add_front(Link_base* p);
16448         // ...
16449     };
16451     template<typename T>
16452     class List : List_base {
16453     public:
16454         void put_front(const T& e) { add_front(new Link<T>{e}); }   // implicit cast to Link_base
16455         T& front() { static_cast<Link<T>*>(first).val; }   // explicit cast back to Link<T>
16456         // ...
16457     };
16459     List<int> li;
16460     List<string> ls;
16462 Now there is only one copy of the operations linking and unlinking elements of a `List`.
16463 The `Link` and `List` classes do nothing but type manipulation.
16465 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.
16467 **Alternative**: Use a [PIMPL](#???) implementation.
16469 ##### Enforcement
16473 ## <a name="SS-variadic"></a>T.var: Variadic template rules
16477 ### <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
16479 ##### Reason
16481 Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs.
16483 ##### Example
16485     ??? printf
16487 ##### Enforcement
16489 * Flag uses of `va_arg` in user code.
16491 ### <a name="Rt-variadic-pass"></a>T.101: ??? How to pass arguments to a variadic template ???
16493 ##### Reason
16495  ???
16497 ##### Example
16499     ??? beware of move-only and reference arguments
16501 ##### Enforcement
16505 ### <a name="Rt-variadic-process"></a>T.102: How to process arguments to a variadic template
16507 ##### Reason
16509  ???
16511 ##### Example
16513     ??? forwarding, type checking, references
16515 ##### Enforcement
16519 ### <a name="Rt-variadic-not"></a>T.103: Don't use variadic templates for homogeneous argument lists
16521 ##### Reason
16523 There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`.
16525 ##### Example
16527     ???
16529 ##### Enforcement
16533 ## <a name="SS-meta"></a>T.meta: Template metaprogramming (TMP)
16535 Templates provide a general mechanism for compile-time programming.
16537 Metaprogramming is programming where at least one input or one result is a type.
16538 Templates offer Turing-complete (modulo memory capacity) duck typing at compile time.
16539 The syntax and techniques needed are pretty horrendous.
16541 ### <a name="Rt-metameta"></a>T.120: Use template metaprogramming only when you really need to
16543 ##### Reason
16545 Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain.
16546 However, there are real-world examples where template metaprogramming provides better performance that any alternative short of expert-level assembly code.
16547 Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code.
16548 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++.
16550 ##### Example, bad
16552     ???
16554 ##### Example, bad
16556     enable_if
16558 Instead, use concepts. But see [How to emulate concepts if you don't have language support](#Rt-emulate).
16560 ##### Example
16562     ??? good
16564 **Alternative**: If the result is a value, rather than a type, use a [`constexpr` function](#Rt-fct).
16566 ##### Note
16568 If you feel the need to hide your template metaprogramming in macros, you have probably gone too far.
16570 ### <a name="Rt-emulate"></a>T.121: Use template metaprogramming primarily to emulate concepts
16572 ##### Reason
16574 Until concepts become generally available, we need to emulate them using TMP.
16575 Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP.
16577 ##### Example
16579     template<typename Iter>
16580         /*requires*/ enable_if<random_access_iterator<Iter>, void>
16581     advance(Iter p, int n) { p += n; }
16583     template<typename Iter>
16584         /*requires*/ enable_if<forward_iterator<Iter>, void>
16585     advance(Iter p, int n) { assert(n >= 0); while (n--) ++p;}
16587 ##### Note
16589 Such code is much simpler using concepts:
16591     void advance(RandomAccessIterator p, int n) { p += n; }
16593     void advance(ForwardIterator p, int n) { assert(n >= 0); while (n--) ++p;}
16595 ##### Enforcement
16599 ### <a name="Rt-tmp"></a>T.122: Use templates (usually template aliases) to compute types at compile time
16601 ##### Reason
16603 Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time.
16605 ##### Note
16607 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
16609 ##### Example
16611     ??? big object / small object optimization
16613 ##### Enforcement
16617 ### <a name="Rt-fct"></a>T.123: Use `constexpr` functions to compute values at compile time
16619 ##### Reason
16621 A function is the most obvious and conventional way of expressing the computation of a value.
16622 Often a `constexpr` function implies less compile-time overhead than alternatives.
16624 ##### Note
16626 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
16628 ##### Example
16630     template<typename T>
16631         // requires Number<T>
16632     constexpr T pow(T v, int n)   // power/exponential
16633     {
16634         T res = 1;
16635         while (n--) res *= v;
16636         return res;
16637     }
16639     constexpr auto f7 = pow(pi, 7);
16641 ##### Enforcement
16643 * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions.
16645 ### <a name="Rt-std-tmp"></a>T.124: Prefer to use standard-library TMP facilities
16647 ##### Reason
16649 Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known.
16651 ##### Example
16653     ???
16655 ##### Enforcement
16659 ### <a name="Rt-lib"></a>T.125: If you need to go beyond the standard-library TMP facilities, use an existing library
16661 ##### Reason
16663 Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community.
16664 Write your own "advanced TMP support" only if you really have to.
16666 ##### Example
16668     ???
16670 ##### Enforcement
16674 ## <a name="SS-temp-other"></a>Other template rules
16676 ### <a name="Rt-name"></a>T.140: Name all operations with potential for reuse
16678 ##### Reason
16680 Documentation, readability, opportunity for reuse.
16682 ##### Example
16684     struct Rec {
16685         string name;
16686         string addr;
16687         int id;         // unique identifier
16688     };
16690     bool same(const Rec& a, const Rec& b)
16691     {
16692         return a.id == b.id;
16693     }
16695     vector<Rec*> find_id(const string& name);    // find all records for "name"
16697     auto x = find_if(vr.begin(), vr.end(),
16698         [&](Rec& r) {
16699             if (r.name.size() != n.size()) return false; // name to compare to is in n
16700             for (int i = 0; i < r.name.size(); ++i)
16701                 if (tolower(r.name[i]) != tolower(n[i])) return false;
16702             return true;
16703         }
16704     );
16706 There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.
16708     bool compare_insensitive(const string& a, const string& b)
16709     {
16710         if (a.size() != b.size()) return false;
16711         for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
16712         return true;
16713     }
16715     auto x = find_if(vr.begin(), vr.end(),
16716         [&](Rec& r) { compare_insensitive(r.name, n); }
16717     );
16719 Or maybe (if you prefer to avoid the implicit name binding to n):
16721     auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };
16723     auto x = find_if(vr.begin(), vr.end(),
16724         [](const Rec& r) { return cmp_to_n(r.name); }
16725     );
16727 ##### Note
16729 whether functions, lambdas, or operators.
16731 ##### Exception
16733 * Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms.
16734 * Lambdas as [initializers](#???)
16736 ##### Enforcement
16738 * (hard) flag similar lambdas
16739 * ???
16741 ### <a name="Rt-lambda"></a>T.141: Use an unnamed lambda if you need a simple function object in one place only
16743 ##### Reason
16745 That makes the code concise and gives better locality than alternatives.
16747 ##### Example
16749     auto earlyUsersEnd = std::remove_if(users.begin(), users.end(),
16750                                         [](const User &a) { return a.id > 100; });
16753 ##### Exception
16755 Naming a lambda can be useful for clarity even if it is used only once.
16757 ##### Enforcement
16759 * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas).
16761 ### <a name="Rt-var"></a>T.142?: Use template variables to simplify notation
16763 ##### Reason
16765 Improved readability.
16767 ##### Example
16769     ???
16771 ##### Enforcement
16775 ### <a name="Rt-nongeneric"></a>T.143: Don't write unintentionally nongeneric code
16777 ##### Reason
16779 Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available.
16781 ##### Example
16783 Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering.
16785     for (auto i = first; i < last; ++i) {   // less generic
16786         // ...
16787     }
16789     for (auto i = first; i != last; ++i) {   // good; more generic
16790         // ...
16791     }
16793 Of course, range-`for` is better still where it does what you want.
16795 ##### Example
16797 Use the least-derived class that has the functionality you need.
16799     class Base {
16800     public:
16801         Bar f();
16802         Bar g();
16803     };
16805     class Derived1 : public Base {
16806     public:
16807         Bar h();
16808     };
16810     class Derived2 : public Base {
16811     public:
16812         Bar j();
16813     };
16815     // bad, unless there is a specific reason for limiting to Derived1 objects only
16816     void my_func(Derived1& param)
16817     {
16818         use(param.f());
16819         use(param.g());
16820     }
16822     // good, uses only Base interface so only commit to that
16823     void my_func(Base& param)
16824     {
16825         use(param.f());
16826         use(param.g());
16827     }
16829 ##### Enforcement
16831 * Flag comparison of iterators using `<` instead of `!=`.
16832 * 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.
16833 * Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type.
16835 ### <a name="Rt-specialize-function"></a>T.144: Don't specialize function templates
16837 ##### Reason
16839 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.
16841 ##### Example
16843     ???
16845 **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).
16847 ##### Enforcement
16849 * Flag all specializations of a function template. Overload instead.
16852 ### <a name="Rt-check-class"></a>T.150: Check that a class matches a concept using `static_assert`
16854 ##### Reason
16856 If you intend for a class to match a concept, verifying that early saves users pain.
16858 ###### Example
16860     class X {
16861         X() = delete;
16862         X(const X&) = default;
16863         X(X&&) = default;
16864         X& operator=(const X&) = default;
16865         // ...
16866     };
16868 Somewhere, possibly in an implementation file, let the compiler check the desired properties of `X`:
16870     static_assert(Default_constructible<X>);    // error: X has no default constructor
16871     static_assert(Copyable<X>);                 // error: we forgot to define X's move constructor
16874 ###### Enforcement
16876 Not feasible.
16878 # <a name="S-cpl"></a>CPL: C-style programming
16880 C and C++ are closely related languages.
16881 They both originate in "Classic C" from 1978 and have evolved in ISO committees since then.
16882 Many attempts have been made to keep them compatible, but neither is a subset of the other.
16884 C rule summary:
16886 * [CPL.1: Prefer C++ to C](#Rcpl-C)
16887 * [CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++](#Rcpl-subset)
16888 * [CPL.3: If you must use C for interfaces, use C++ in the code using such interfaces](#Rcpl-interface)
16890 ### <a name="Rcpl-C"></a>CPL.1: Prefer C++ to C
16892 ##### Reason
16894 C++ provides better type checking and more notational support.
16895 It provides better support for high-level programming and often generates faster code.
16897 ##### Example
16899     char ch = 7;
16900     void* pv = &ch;
16901     int* pi = pv;   // not C++
16902     *pi = 999;      // overwrite sizeof(int) bytes near &ch
16904 The rules for implicit casting to and from `void*` in C are subtle and unenforced.
16905 In particular, this example violates a rule against converting to a type with stricter alignment.
16907 ##### Enforcement
16909 Use a C++ compiler.
16911 ### <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++
16913 ##### Reason
16915 That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C."
16917 ##### Example
16919     int* p1 = malloc(10 * sizeof(int));                      // not C++
16920     int* p2 = static_cast<int*>(malloc(10 * sizeof(int)));   // not C, C-style C++
16921     int* p3 = new int[10];                                   // not C
16922     int* p4 = (int*) malloc(10 * sizeof(int));               // both C and C++
16924 ##### Enforcement
16926 * Flag if using a build mode that compiles code as C.
16928   * The C++ compiler will enforce that the code is valid C++ unless you use C extension options.
16930 ### <a name="Rcpl-interface"></a>CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces
16932 ##### Reason
16934 C++ is more expressive than C and offers better support for many types of programming.
16936 ##### Example
16938 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.
16939 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.
16941 ##### Example
16943 You can call C from C++:
16945     // in C:
16946     double sqrt(double);
16948     // in C++:
16949     extern "C" double sqrt(double);
16951     sqrt(2);
16953 ##### Example
16955 You can call C++ from C:
16957     // in C:
16958     X call_f(struct Y*, int);
16960     // in C++:
16961     extern "C" X call_f(Y* p, int i)
16962     {
16963         return p->f(i);   // possibly a virtual function call
16964     }
16966 ##### Enforcement
16968 None needed
16970 # <a name="S-source"></a>SF: Source files
16972 Distinguish between declarations (used as interfaces) and definitions (used as implementations).
16973 Use header files to represent interfaces and to emphasize logical structure.
16975 Source file rule summary:
16977 * [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)
16978 * [SF.2: A `.h` file may not contain object definitions or non-inline function definitions](#Rs-inline)
16979 * [SF.3: Use `.h` files for all declarations used in multiple source files](#Rs-declaration-header)
16980 * [SF.4: Include `.h` files before other declarations in a file](#Rs-include-order)
16981 * [SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface](#Rs-consistency)
16982 * [SF.6: Use `using namespace` directives for transition, for foundation libraries (such as `std`), or within a local scope (only)](#Rs-using)
16983 * [SF.7: Don't write `using namespace` in a header file](#Rs-using-directive)
16984 * [SF.8: Use `#include` guards for all `.h` files](#Rs-guards)
16985 * [SF.9: Avoid cyclic dependencies among source files](#Rs-cycles)
16987 * [SF.20: Use `namespace`s to express logical structure](#Rs-namespace)
16988 * [SF.21: Don't use an unnamed (anonymous) namespace in a header](#Rs-unnamed)
16989 * [SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities](#Rs-unnamed2)
16991 ### <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
16993 ##### Reason
16995 It's a longstanding convention.
16996 But consistency is more important, so if your project uses something else, follow that.
16998 ##### Note
17000 This convention reflects a common use pattern:
17001 Headers are more often shared with C to compile as both C++ and C, which typically uses `.h`,
17002 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.
17003 On the other hand, implementation files are rarely shared with C and so should typically be distinguished from `.c` files,
17004 so it's normally best to name all C++ implementation files something else (such as `.cpp`).
17006 The specific names `.h` and `.cpp` are not required (just recommended as a default) and other names are in widespread use.
17007 Examples are `.hh`, `.C`, and `.cxx`. Use such names equivalently.
17008 In this document, we refer to `.h` and `.cpp` as a shorthand for header and implementation files,
17009 even though the actual extension may be different.
17011 Your IDE (if you use one) may have strong opinions about suffices.
17013 ##### Example
17015     // foo.h:
17016     extern int a;   // a declaration
17017     extern void foo();
17019     // foo.cpp:
17020     int a;   // a definition
17021     void foo() { ++a; }
17023 `foo.h` provides the interface to `foo.cpp`. Global variables are best avoided.
17025 ##### Example, bad
17027     // foo.h:
17028     int a;   // a definition
17029     void foo() { ++a; }
17031 `#include <foo.h>` twice in a program and you get a linker error for two one-definition-rule violations.
17033 ##### Enforcement
17035 * Flag non-conventional file names.
17036 * Check that `.h` and `.cpp` (and equivalents) follow the rules below.
17038 ### <a name="Rs-inline"></a>SF.2: A `.h` file may not contain object definitions or non-inline function definitions
17040 ##### Reason
17042 Including entities subject to the one-definition rule leads to linkage errors.
17044 ##### Example
17046     // file.h:
17047     namespace Foo {
17048         int x = 7;
17049         int xx() { return x+x; }
17050     }
17052     // file1.cpp:
17053     #include <file.h>
17054     // ... more ...
17056      // file2.cpp:
17057     #include <file.h>
17058     // ... more ...
17060 Linking `file1.cpp` and `file2.cpp` will give two linker errors.
17062 **Alternative formulation**: A `.h` file must contain only:
17064 * `#include`s of other `.h` files (possibly with include guards)
17065 * templates
17066 * class definitions
17067 * function declarations
17068 * `extern` declarations
17069 * `inline` function definitions
17070 * `constexpr` definitions
17071 * `const` definitions
17072 * `using` alias definitions
17073 * ???
17075 ##### Enforcement
17077 Check the positive list above.
17079 ### <a name="Rs-declaration-header"></a>SF.3: Use `.h` files for all declarations used in multiple source files
17081 ##### Reason
17083 Maintainability. Readability.
17085 ##### Example, bad
17087     // bar.cpp:
17088     void bar() { cout << "bar\n"; }
17090     // foo.cpp:
17091     extern void bar();
17092     void foo() { bar(); }
17094 A maintainer of `bar` cannot find all declarations of `bar` if its type needs changing.
17095 The user of `bar` cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker.
17097 ##### Enforcement
17099 * Flag declarations of entities in other source files not placed in a `.h`.
17101 ### <a name="Rs-include-order"></a>SF.4: Include `.h` files before other declarations in a file
17103 ##### Reason
17105 Minimize context dependencies and increase readability.
17107 ##### Example
17109     #include <vector>
17110     #include <algorithm>
17111     #include <string>
17113     // ... my code here ...
17115 ##### Example, bad
17117     #include <vector>
17119     // ... my code here ...
17121     #include <algorithm>
17122     #include <string>
17124 ##### Note
17126 This applies to both `.h` and `.cpp` files.
17128 ##### Note
17130 There is an argument for insulating code from declarations and macros in header files by `#including` headers *after* the code we want to protect
17131 (as in the example labeled "bad").
17132 However
17134 * that only works for one file (at one level): Use that technique in a header included with other headers and the vulnerability reappears.
17135 * a namespace (an "implementation namespace") can protect against many context dependencies.
17136 * full protection and flexibility require [modules](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4592.pdf).
17137 [See also](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0141r0.pdf).
17140 ##### Enforcement
17142 Easy.
17144 ### <a name="Rs-consistency"></a>SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface
17146 ##### Reason
17148 This enables the compiler to do an early consistency check.
17150 ##### Example, bad
17152     // foo.h:
17153     void foo(int);
17154     int bar(long);
17155     int foobar(int);
17157     // foo.cpp:
17158     void foo(int) { /* ... */ }
17159     int bar(double) { /* ... */ }
17160     double foobar(int);
17162 The errors will not be caught until link time for a program calling `bar` or `foobar`.
17164 ##### Example
17166     // foo.h:
17167     void foo(int);
17168     int bar(long);
17169     int foobar(int);
17171     // foo.cpp:
17172     #include <foo.h>
17174     void foo(int) { /* ... */ }
17175     int bar(double) { /* ... */ }
17176     double foobar(int);   // error: wrong return type
17178 The return-type error for `foobar` is now caught immediately when `foo.cpp` is compiled.
17179 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.
17181 ##### Enforcement
17185 ### <a name="Rs-using"></a>SF.6: Use `using namespace` directives for transition, for foundation libraries (such as `std`), or within a local scope (only)
17187 ##### Reason
17189  `using namespace` can lead to name clashes, so it should be used sparingly.
17190  However, it is not always possible to qualify every name from a namespace in user code (e.g., during transition)
17191  and sometimes a namespace is so fundamental and prevalent in a code base, that consistent qualification would be verbose and distracting.
17193 ##### Example
17195     #include<string>
17196     #include<vector>
17197     #include<iostream>
17198     #include<memory>
17199     #include<algorithm>
17201     using namespace std;
17203     // ...
17205 Here (obviously), the standard library is used pervasively and apparently no other library is used, so requiring `std::` everywhere
17206 could be distracting.
17208 ##### Example
17210 The use of `using namespace std;` leaves the programmer open to a name clash with a name from the standard library
17212     #include<cmath>
17213     using namespace std;
17215     int g(int x)
17216     {
17217         int sqrt = 7;
17218         // ...
17219         return sqrt(x); // error
17220     }
17222 However, this is not particularly likely to lead to a resolution that is not an error and
17223 people who use `using namespace std` are supposed to know about `std` and about this risk.
17225 ##### Note
17227 A `.cpp` file is a form of local scope.
17228 There is little difference in the opportunities for name clashes in an N-line `.cpp` containing a `using namespace X`,
17229 an N-line function containing a `using namespace X`,
17230 and M functions each containing a `using namespace X`with N lines of code in total.
17232 ##### Note
17234 [Don't write `using namespace` in a header file](#Rs-using-directive).
17236 ##### Enforcement
17238 Flag multiple `using namespace` directives for different namespaces in a single source file.
17240 ### <a name="Rs-using-directive"></a>SF.7: Don't write `using namespace` in a header file
17242 ##### Reason
17244 Doing so takes away an `#include`r's ability to effectively disambiguate and to use alternatives.
17246 ##### Example
17248     // bad.h
17249     #include <iostream>
17250     using namespace std; // bad
17252     // user.cpp
17253     #include "bad.h"
17254     
17255     bool copy(/*... some parameters ...*/);    // some function that happens to be named copy
17257     int main() {
17258         copy(/*...*/);    // now overloads local ::copy and std::copy, could be ambiguous
17259     }
17261 ##### Enforcement
17263 Flag `using namespace` at global scope in a header file.
17265 ### <a name="Rs-guards"></a>SF.8: Use `#include` guards for all `.h` files
17267 ##### Reason
17269 To avoid files being `#include`d several times.
17271 ##### Example
17273     // file foobar.h:
17274     #ifndef FOOBAR_H
17275     #define FOOBAR_H
17276     // ... declarations ...
17277     #endif // FOOBAR_H
17279 ##### Enforcement
17281 Flag `.h` files without `#include` guards.
17283 ### <a name="Rs-cycles"></a>SF.9: Avoid cyclic dependencies among source files
17285 ##### Reason
17287 Cycles complicates comprehension and slows down compilation.
17288 Complicates conversion to use language-supported modules (when they become available).
17290 ##### Note
17292 Eliminate cycles; don't just break them with `#include` guards.
17294 ##### Example, bad
17296     // file1.h:
17297     #include "file2.h"
17299     // file2.h:
17300     #include "file3.h"
17302     // file3.h:
17303     #include "file1.h"
17305 ##### Enforcement
17307 Flag all cycles.
17309 ### <a name="Rs-namespace"></a>SF.20: Use `namespace`s to express logical structure
17311 ##### Reason
17313  ???
17315 ##### Example
17317     ???
17319 ##### Enforcement
17323 ### <a name="Rs-unnamed"></a>SF.21: Don't use an unnamed (anonymous) namespace in a header
17325 ##### Reason
17327 It is almost always a bug to mention an unnamed namespace in a header file.
17329 ##### Example
17331     ???
17333 ##### Enforcement
17335 * Flag any use of an anonymous namespace in a header file.
17337 ### <a name="Rs-unnamed2"></a>SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities
17339 ##### Reason
17341 Nothing external can depend on an entity in a nested unnamed namespace.
17342 Consider putting every definition in an implementation source file in an unnamed namespace unless that is defining an "external/exported" entity.
17344 ##### Example
17346 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.
17348     ???
17350 ##### Enforcement
17352 * ???
17354 # <a name="S-stdlib"></a>SL: The Standard Library
17356 Using only the bare language, every task is tedious (in any language).
17357 Using a suitable library any task can be reasonably simple.
17359 The standard library has steadily grown over the years.
17360 Its description in the standard is now larger than that of the language features.
17361 So, it is likely that this library section of the guidelines will eventually grow in size to equal or exceed all the rest.
17363 << ??? We need another level of rule numbering ??? >>
17365 C++ Standard library component summary:
17367 * [SL.con: Containers](#SS-con)
17368 * [SL.str: String](#SS-string)
17369 * [SL.io: Iostream](#SS-io)
17370 * [SL.regex: Regex](#SS-regex)
17371 * [SL.chrono: Time](#SS-chrono)
17372 * [SL.C: The C standard library](#SS-clib)
17374 Standard-library rule summary:
17376 * [SL.1: Use libraries wherever possible](#Rsl-lib)
17377 * [SL.2: Prefer the standard library to other libraries](#Rsl-sl)
17378 * [SL.3: Do not add non-standard entities to namespace `std`](#sl-std)
17379 * ???
17381 ### <a name="Rsl-lib"></a>SL.1:  Use libraries wherever possible
17383 ##### Reason
17385 Save time. Don't re-invent the wheel.
17386 Don't replicate the work of others.
17387 Benefit from other people's work when they make improvements.
17388 Help other people when you make improvements.
17390 ### <a name="Rsl-sl"></a>SL.2: Prefer the standard library to other libraries
17392 ##### Reason
17394 More people know the standard library.
17395 It is more likely to be stable, well-maintained, and widely available than your own code or most other libraries.
17398 ### <a name="sl-std"></a>SL.3: Do not add non-standard entities to namespace `std`
17400 ##### Reason
17402 Adding to `std` may change the meaning of otherwise standards conforming code.
17403 Additions to `std` may clash with future versions of the standard.
17405 ##### Example
17407     ???
17409 ##### Enforcement
17411 Possible, but messy and likely to cause problems with platforms.
17414 ## <a name="SS-con"></a>SL.con: Containers
17418 Container rule summary:
17420 * [SL.con.1: Prefer using STL `array` or `vector` instead of a C array](#Rsl-arrays)
17421 * [SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container](#Rsl-vector)
17422 *  ???
17424 ### <a name="Rsl-arrays"></a>SL.con.1: Prefer using STL `array` or `vector` instead of a C array
17426 ##### Reason
17428 C arrays are less safe, and have no advantages over `array` and `vector`.
17429 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.
17430 Also, like a built-in array, a stack-allocated `std::array` keeps its elements on the stack.
17431 For a variable-length array, use `std::vector`, which additionally can change its size and handles memory allocation.
17433 ##### Example
17435     int v[SIZE];                        // BAD
17437     std::array<int, SIZE> w;             // ok
17439 ##### Example
17441     int* v = new int[initial_size];     // BAD, owning raw pointer
17442     delete[] v;                         // BAD, manual delete
17444     std::vector<int> w(initial_size);   // ok
17446 ##### Enforcement
17448 * 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`.
17450 ### <a name="Rsl-vector"></a>SL.con.2: Prefer using STL `vector` by default unless you have a reason to use a different container
17452 ##### Reason
17454 `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).
17455 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`.
17457 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.
17459 ##### Note
17461 `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.
17463 ##### Exceptions
17465 If you have a good reason to use another container, use that instead. For example:
17467 * If `vector` suits your needs but you don't need the container to be variable size, use `array` instead.
17469 * 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.
17471 ##### Enforcement
17473 * 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.
17475 ## <a name="SS-string"></a>SL.str: String
17477 Text manipulation is a huge topic.
17478 `std::string` doesn't cover all of it.
17479 This section primarily tries to clarify `std::string`'s relation to `char*`, `zstring`, `string_view`, and `gsl::string_span`.
17480 The important issue of non-ASCII character sets and encodings (e.g., `wchar_t`, Unicode, and UTF-8) will be covered elsewhere.
17482 See also [regular expressions](#SS-regex).
17484 Here, we use "sequence of characters" or "string" to refer to a sequence of characters meant to be read as text (somehow, eventually).
17485 We don't consider 
17487 String summary:
17489 * [SL.str.1: Use `std::string` to own character sequences](#Rstr-string)
17490 * [SL.str.2: Use `std::string_view` or `gsl::string_span` to refer to character sequences](#Rstr-view)
17491 * [SL.str.3: Use `zstring` or `czstring` to refer to a C-style, zero-terminated, sequence of characters](#Rstr-zstring)
17492 * [SL.str.4: Use `char*` to refer to a single character](#Rstr-char*)
17493 * [Sl.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters](#Rstr-byte)
17495 * [Sl.str.10: Use `std::string` when you need to perform locale-sensitive string operations](#Rstr-locale)
17496 * [Sl.str.11: Use `gsl::string_span` rather than `std::string_view` when you need to mutate a string](#Rstr-span)
17497 * [Sl.str.12: Use the `s` suffix for string literals meant to be standard-library `string`s](#Rstr-s)
17499 See also
17501 * [F.24 span](#Rf-range)
17502 * [F.25 zstring](#Rf-zstring)
17505 ### <a name="Rstr-string"></a>SL.str.1: Use `std::string` to own character sequences
17507 ##### Reason
17509 `string` correctly handles allocation, ownership, copying, gradual expansion, and offers a variety of useful operations.
17511 ##### Example
17513     vector<string> read_until(const string& terminator)
17514     {
17515         vector<string> res;
17516         for (string s; cin >> s && s != terminator; ) // read a word
17517             res.push_back(s);
17518         return res;
17519     }
17521 Note how `>>` and `!=` are provided for `string` (as examples of useful operations) and there are no explicit
17522 allocations, deallocations, or range checks (`string` takes care of those).
17524 In C++17, we might use `string_view` as the argument, rather than `const string *` to allow more flexibility to callers:
17526     vector<string> read_until(string_view terminator)   // C++17
17527     {
17528         vector<string> res;
17529         for (string s; cin >> s && s != terminator; ) // read a word
17530             res.push_back(s);
17531         return res;
17532     }
17534 The `gsl::string_span` is a current alternative offering most of the benefits of `string_span` for simple examples:
17536     vector<string> read_until(string_span terminator)
17537     {
17538         vector<string> res;
17539         for (string s; cin >> s && s != terminator; ) // read a word
17540             res.push_back(s);
17541         return res;
17542     }
17544 ##### Example, bad
17546 Don't use C-style strings for operations that require non-trivial memory management
17548     char* cat(const char* s1, const char* s2)   // beware!
17549         // return s1 + '.' + s2
17550     {
17551         int l1 = strlen(s1);
17552         int l2 = strlen(s2);
17553         char* p = (char*)malloc(l1+l2+2);
17554         strcpy(p, s1, l1);
17555         p[l1] = '.';
17556         strcpy(p+l1+1, s2, l2);
17557         p[l1+l2+1] = 0;
17558         return res;
17559     }
17561 Did we get that right?
17562 Will the caller remember to `free()` the returned pointer?
17563 Will this code pass a security review?
17565 ##### Note
17567 Do not assume that `string` is slower than lower-level techniques without measurement and remember than not all code is performance critical.
17568 [Don't optimize prematurely](#Rper-Knuth)
17570 ##### Enforcement
17574 ### <a name="Rstr-view"></a>SL.str.2: Use `std::string_view` or `gsl::string_span` to refer to character sequences
17576 ##### Reason
17578 `std::string_view` or `gsl::string_span` provides simple and (potentially) safe access to character sequences independently of how
17579 those sequences are allocated and stored.
17581 ##### Example
17583     vector<string> read_until(string_span terminator);
17585     void user(zstring p, const string& s, string_span ss)
17586     {
17587         auto v1 = read_until(p);
17588         auto v2 = read_until(s);
17589         auto v3 = read_until(ss);
17590         // ...
17591     }
17593 ##### Note
17595 `std::string_view` (C++17) is read only.
17597 ##### Enforcement
17601 ### <a name="Rstr-zstring"></a>SL.str.3: Use `zstring` or `czstring` to refer to a C-style, zero-terminated, sequence of characters
17603 ##### Reason
17605 Readability.
17606 Statement of intent.
17607 A plain `char*` can be a pointer to a single character, a pointer to an array of characters, a pointer to a C-style (zero terminated) string, or even to a small integer.
17608 Distinguishing these alternatives prevents misunderstandings and bugs.
17610 ##### Example
17612     void f1(const char* s); // s is probably a string
17614 All we know is that it is supposed to be the nullptr or point to at least one character
17616     void f1(zstring s);     // s is a C-style string or the nullptr
17617     void f1(czstring s);    // s is a C-style string that is not the nullptr
17618     void f1(std::byte* s);  // s is a pointer to a byte (C++17)
17620 ##### Note
17622 Don't convert a C-style string to `string` unless there is a reason to.
17624 ##### Note
17626 Like any other "plain pointer", a `zstring` should not represent ownership.
17628 ##### Note
17630 There are billions of lines of C++ "out there", most use `char*` and `const char*` without documenting intent.
17631 They are used in a wide variety of ways, including to represent ownership and as generic pointers to memory (instead of `void*`).
17632 It is hard to separate these uses, so this guideline is hard to follow.
17633 This is one of the major sources of bugs in C and C++ programs, so it is worthwhile to follow this guideline wherever feasible..
17635 ##### Enforcement
17637 * Flag uses of `[]` on a `char*`
17638 * Flag uses of `delete` on a `char*`
17639 * Flag uses of `free()` on a `char*`
17641 ### <a name="Rstr-char*"></a>SL.str.4: Use `char*` to refer to a single character
17643 ##### Reason
17645 The variety of uses of `char*` in current code is a major source of errors.
17647 ##### Example, bad
17649     char arr[] = {'a', 'b', 'c'};
17651     void print(const char* p)
17652     {
17653         cout << p << '\n';
17654     }
17656     void use()
17657     {
17658         print(arr);   // run-time error; potentially very bad
17659     }
17661 The array `arr` is not a C-style string because it is not zero-terminated.
17663 ##### Alternative
17665 See [`zstring`](#Rstr-zstring), [`string`](#Rstr-string), and [`string_span`](#Rstr-view).
17667 ##### Enforcement
17668   
17669 * Flag uses of `[]` on a `char*`
17671 ### <a name="Rstr-byte"></a>Sl.str.5: Use `std::byte` to refer to byte values that do not necessarily represent characters
17673 ##### Reason
17675 Use of `char*` to represent a pointer to something that is not necessarily a character causes confusion
17676 and disables valuable optimizations.
17678 ##### Example
17680     ???
17682 ##### Note
17684 C++17
17686 ##### Enforcement
17689     
17691 ### <a name="Rstr-locale"></a>Sl.str.10: Use `std::string` when you need to perform locale-sensitive string operations
17693 ##### Reason
17695 `std::string` supports standard-library [`locale` facilities](#Rstr-locale)
17697 ##### Example
17699     ???
17701 ##### Note
17705 ##### Enforcement
17709 ### <a name="Rstr-span"></a>Sl.str.11: Use `gsl::string_span` rather than `std::string_view` when you need to mutate a string
17711 ##### Reason
17713 `std::string_view` is read-only.
17715 ##### Example
17719 ##### Note
17723 ##### Enforcement
17725 The compiler will flag attempts to write to a `string_view`.
17727 ### <a name="Rstr-s"></a>Sl.str.12: Use the `s` suffix for string literals meant to be standard-library `string`s
17729 ##### Reason
17731 Direct expression of an idea minimizes mistakes.
17733 ##### Example
17735     auto pp1 = make_pair("Tokyo", 9.00);         // {C-style string,double} intended?
17736     pair<string, double> pp2 = {"Tokyo", 9.00};  // a bit verbose
17737     auto pp3 = make_pair("Tokyo"s, 9.00);        // {std::string,double}    // C++17
17738     pair pp4 = {"Tokyo"s, 9.00};                 // {std::string,double}    // C++17
17741 ##### Note
17743 C++17
17745 ##### Enforcement
17750 ## <a name="SS-io"></a>SL.io: Iostream
17752 `iostream`s is a type safe, extensible, formatted and unformatted I/O library for streaming I/O.
17753 It supports multiple (and user extensible) buffering strategies and multiple locales.
17754 It can be used for conventional I/O, reading and writing to memory (string streams),
17755 and user-defines extensions, such as streaming across networks (asio: not yet standardized).
17757 Iostream rule summary:
17759 * [SL.io.1: Use character-level input only when you have to](#Rio-low)
17760 * [SL.io.2: When reading, always consider ill-formed input](#Rio-validate)
17761 * [SL.io.3: Prefer iostreams for I/O](#Rio-streams)
17762 * [SL.io.10: Unless you use `printf`-family functions call `ios_base::sync_with_stdio(false)`](#Rio-sync) 
17763 * [SL.io.50: Avoid `endl`](#Rio-endl)
17764 * [???](#???)
17766 ### <a name="Rio-low"></a>SL.io.1: Use character-level input only when you have to
17768 ##### Reason
17770 Unless you genuinely just deal with individual characters, using character-level input leads to the user code performing potentially error-prone
17771 and potentially inefficient composition of tokens out of characters.
17773 ##### Example
17775     char c;
17776     char buf[128];
17777     int i = 0;
17778     while (cin.get(c) && !isspace(c) && i < 128)
17779         buf[i++] = c;
17780     if (i == 128) {
17781         // ... handle too long string ....
17782     }
17784 Better (much simpler and probably faster):
17786     string s;
17787     s.reserve(128);
17788     cin >> s;
17790 and the `reserve(128)` is probably not worthwhile.
17792 ##### Enforcement
17797 ### <a name="Rio-validate"></a>SL.io.2: When reading, always consider ill-formed input
17799 ##### Reason
17801 Errors are typically best handled as soon as possible.
17802 If input isn't validated, every function must be written to cope with bad data (and that is not practical).
17804 ###### Example
17806     ???
17808 ##### Enforcement
17812 ### <a name="Rio-streams"></a>SL.io.3: Prefer `iostream`s for I/O
17814 ##### Reason
17816 `iostream`s are safe, flexible, and extensible.
17818 ##### Example
17820     // write a complex number:
17821     complex<double> z{ 3, 4 };
17822     cout << z << '\n';
17824 `complex` is a user defined type and its I/O is defined without modifying the `iostream` library.
17826 ##### Example
17828     // read a file of complex numbers:
17829     for (complex<double> z; cin >> z; )
17830         v.push_back(z);
17832 ##### Exception
17834 ??? performance ???
17836 ##### Discussion: `iostream`s vs. the `printf()` family
17838 It is often (and often correctly) pointed out that the `printf()` family has two advantages compared to `iostream`s:
17839 flexibility of formatting and performance.
17840 This has to be weighed against `iostream`s advantages of extensibility to handle user-defined types, resilient against security violations,
17841 implicit memory management, and `locale` handling.
17843 If you need I/O performance, you can almost always do better than `printf()`.
17845 `gets()` `scanf()` using `s`, and `printf()` using `%s` are security hazards (vulnerable to buffer overflow and generally error-prone).
17846 In C11, they are replaced by `gets_s()`, `scanf_s()`, and `printf_s()` as safer alternatives, but they are still not type safe.
17848 ##### Enforcement
17850 Optionally flag `<cstdio>` and `<stdio.h>`.
17852 ### <a name="Rio-sync"></a>SL.io.10: Unless you use `printf`-family functions call `ios_base::sync_with_stdio(false)`
17854 ##### Reason
17856 Synchronizing `iostreams` with `printf-style` I/O can be costly.
17857 `cin` and `cout` are by default synchronized with `printf`.
17859 ##### Example
17861     int main()
17862     {
17863         ios_base::sync_with_stdio(false);
17864         // ... use iostreams ...
17865     }
17867 ##### Enforcement
17871 ### <a name="Rio-endl"></a>SL.io.50: Avoid `endl`
17873 ### Reason
17875 The `endl` manipulator is mostly equivalent to `'\n'` and `"\n"`;
17876 as most commonly used it simply slows down output by doing redundant `flush()`s.
17877 This slowdown can be significant compared to `printf`-style output.
17879 ##### Example
17881     cout << "Hello, World!" << endl;    // two output operations and a flush
17882     cout << "Hello, World!\n";          // one output operation and no flush
17884 ##### Note
17886 For `cin`/`cout` (and equivalent) interaction, there is no reason to flush; that's done automatically.
17887 For writing to a file, there is rarely a need to `flush`.
17889 ##### Note
17891 Apart from the (occasionally important) issue of performance,
17892 the choice between `'\n'` and `endl` is almost completely aesthetic.
17894 ## <a name="SS-regex"></a>SL.regex: Regex
17896 `<regex>` is the standard C++ regular expression library.
17897 It supports a variety of regular expression pattern conventions.
17899 ## <a name="SS-chrono"></a>SL.chrono: Time
17901 `<chrono>` (defined in namespace `std::chrono`) provides the notions of `time_point` and `duration` together with functions for
17902 outputting time in various units.
17903 It provides clocks for registering `time_points`.
17905 ## <a name="SS-clib"></a>SL.C: The C standard library
17909 C standard library rule summary:
17911 * [S.C.1: Don't use setjmp/longjmp](#Rclib-jmp)
17912 * [???](#???)
17913 * [???](#???)
17915 ### <a name="Rclib-jmp"></a>SL.C.1: Don't use setjmp/longjmp
17917 ##### Reason
17919 a `longjmp` ignores destructors, thus invalidating all resource-management strategies relying on RAII
17921 ##### Enforcement
17923 Flag all occurrences of `longjmp`and `setjmp`
17927 # <a name="S-A"></a>A: Architectural Ideas
17929 This section contains ideas about higher-level architectural ideas and libraries.
17931 Architectural rule summary:
17933 * [A.1 Separate stable from less stable part of code](#Ra-stable)
17934 * [A.2 Express potentially reusable parts as a library](#Ra-lib)
17935 * [A.4 There should be no cycles among libraries](#?Ra-dag)
17936 * [???](#???)
17937 * [???](#???)
17938 * [???](#???)
17939 * [???](#???)
17940 * [???](#???)
17941 * [???](#???)
17943 ### <a name="Ra-stable"></a>A.1 Separate stable from less stable part of code
17947 ### <a name="Ra-lib"></a>A.2 Express potentially reusable parts as a library
17949 ##### Reason
17951 ##### Note
17953 A library is a collection of declarations and definitions maintained, documented, and shipped together.
17954 A library could be a set of headers (a "header only library") or a set of headers plus a set of object files.
17955 A library can be statically or dynamically linked into a program, or it may be `#included`
17958 ### <a name="Ra-dag"></a>A.4 There should be no cycles among libraries
17960 ##### Reason
17962 * A cycle implies complication of the build process.
17963 * Cycles are hard to understand and may introduce indeterminism (unspecified behavior).
17965 ##### Note
17967 A library can contain cyclic references in the definition of its components.
17968 For example:
17970     ???
17972 However, a library should not depend on another that depends on it.
17975 # <a name="S-not"></a>NR: Non-Rules and myths
17977 This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend.
17978 We know full well that there have been times and places where these rules made sense, and we have used them ourselves at times.
17979 However, in the context of the styles of programming we recommend and support with the guidelines, these "non-rules" would do harm.
17981 Even today, there can be contexts where the rules make sense.
17982 For example, lack of suitable tool support can make exceptions unsuitable in hard-real-time systems,
17983 but please don't blindly trust "common wisdom" (e.g., unsupported statements about "efficiency");
17984 such "wisdom" may be based on decades-old information or experienced from languages with very different properties than C++
17985 (e.g., C or Java).
17987 The positive arguments for alternatives to these non-rules are listed in the rules offered as "Alternatives".
17989 Non-rule summary:
17991 * [NR.1: Don't: All declarations should be at the top of a function](#Rnr-top)
17992 * [NR.2: Don't: Have only a single `return`-statement in a function](#Rnr-single-return)
17993 * [NR.3: Don't: Don't use exceptions](#Rnr-no-exceptions)
17994 * [NR.4: Don't: Place each class declaration in its own source file](#Rnr-lots-of-files)
17995 * [NR.5: Don't: Don't do substantive work in a constructor; instead use two-phase initialization](#Rnr-two-phase-init)
17996 * [NR.6: Don't: Place all cleanup actions at the end of a function and `goto exit`](#Rnr-goto-exit)
17997 * [NR.7: Don't: Make all data members `protected`](#Rnr-protected-data)
17998 * ???
18000 ### <a name="Rnr-top"></a>NR.1: Don't: All declarations should be at the top of a function
18002 ##### Reason (not to follow this rule)
18004 This rule is a legacy of old programming languages that didn't allow initialization of variables and constants after a statement.
18005 This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
18007 ##### Example, bad
18009     int use(int x)
18010     {
18011         int i;
18012         char c;
18013         double d;
18015         // ... some stuff ...
18017         if (x < i) {
18018             // ...
18019             i = f(x, d);
18020         }
18021         if (i < x) {
18022             // ...
18023             i = g(x, c);
18024         }
18025         return i;
18026     }
18028 The larger the distance between the uninitialized variable and its use, the larger the chance of a bug.
18029 Fortunately, compilers catch many "used before set" errors.
18030 Unfortunately, compilers cannot catch all such errors and unfortunately, the bugs aren't always as simple to spot as in this small example.
18033 ##### Alternative
18035 * [Always initialize an object](#Res-always)
18036 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
18038 ### <a name="Rnr-single-return"></a>NR.2: Don't: Have only a single `return`-statement in a function
18040 ##### Reason (not to follow this rule)
18042 The single-return rule can lead to unnecessarily convoluted code and the introduction of extra state variables.
18043 In particular, the single-return rule makes it harder to concentrate error checking at the top of a function.
18045 ##### Example
18047     template<class T>
18048     //  requires Number<T>
18049     string sign(T x)
18050     {
18051         if (x < 0)
18052             return "negative";
18053         else if (x > 0)
18054             return "positive";
18055         return "zero";
18056     }
18058 to use a single return only we would have to do something like
18060     template<class T>
18061     //  requires Number<T>
18062     string sign(T x)        // bad
18063     {
18064         string res;
18065         if (x < 0)
18066             res = "negative";
18067         else if (x > 0)
18068             res = "positive";
18069         else
18070             res = "zero";
18071         return res;
18072     }
18074 This is both longer and likely to be less efficient.
18075 The larger and more complicated the function is, the more painful the workarounds get.
18076 Of course many simple functions will naturally have just one `return` because of their simpler inherent logic.
18078 ##### Example
18080     int index(const char* p)
18081     {
18082         if (p == nullptr) return -1;  // error indicator: alternatively "throw nullptr_error{}"
18083         // ... do a lookup to find the index for p
18084         return i;
18085     }
18087 If we applied the rule, we'd get something like
18089     int index2(const char* p)
18090     {
18091         int i;
18092         if (p == nullptr)
18093             i = -1;  // error indicator
18094         else {
18095             // ... do a lookup to find the index for p
18096         }
18097         return i;
18098     }
18100 Note that we (deliberately) violated the rule against uninitialized variables because this style commonly leads to that.
18101 Also, this style is a temptation to use the [goto exit](#Rnr-goto-exit) non-rule.
18103 ##### Alternative
18105 * Keep functions short and simple
18106 * Feel free to use multiple `return` statements (and to throw exceptions).
18108 ### <a name="Rnr-no-exceptions"></a>NR.3: Don't: Don't use exceptions
18110 ##### Reason (not to follow this rule)
18112 There seem to be three main reasons given for this non-rule:
18114 * exceptions are inefficient
18115 * exceptions lead to leaks and errors
18116 * exception performance is not predictable
18118 There is no way we can settle this issue to the satisfaction of everybody.
18119 After all, the discussions about exceptions have been going on for 40+ years.
18120 Some languages cannot be used without exceptions, but others do not support them.
18121 This leads to strong traditions for the use and non-use of exceptions, and to heated debates.
18123 However, we can briefly outline why we consider exceptions the best alternative for general-purpose programming
18124 and in the context of these guidelines.
18125 Simple arguments for and against are often inconclusive.
18126 There are specialized applications where exceptions indeed can be inappropriate
18127 (e.g., hard-real time systems without support for reliable estimates of the cost of handling an exception).
18129 Consider the major objections to exceptions in turn
18131 * Exceptions are inefficient:
18132 Compared to what?
18133 When comparing make sure that the same set of errors are handled and that they are handled equivalently.
18134 In particular, do not compare a program that immediately terminate on seeing an error with a program
18135 that carefully cleans up resources before logging an error.
18136 Yes, some systems have poor exception handling implementations; sometimes, such implementations force us to use
18137 other error-handling approaches, but that's not a fundamental problem with exceptions.
18138 When using an efficiency argument - in any context - be careful that you have good data that actually provides
18139 insight into the problem under discussion.
18140 * Exceptions lead to leaks and errors.
18141 They do not.
18142 If your program is a rat's nest of pointers without an overall strategy for resource management,
18143 you have a problem whatever you do.
18144 If your system consists of a million lines of such code,
18145 you probably will not be able to use exceptions,
18146 but that's a problem with excessive and undisciplined pointer use, rather than with exceptions.
18147 In our opinion, you need RAII to make exception-based error handling simple and safe -- simpler and safer than alternatives.
18148 * Exception performance is not predictable
18149 If you are in a hard-real-time system where you must guarantee completion of a task in a given time,
18150 you need tools to back up such guarantees.
18151 As far as we know such tools are not available (at least not to most programmers).
18153 Many, possibly most, problems with exceptions stem from historical needs to interact with messy old code.
18155 The fundamental arguments for the use of exceptions are
18157 * They clearly separates error return from ordinary return
18158 * They cannot be forgotten or ignored
18159 * They can be used systematically
18161 Remember
18163 * Exceptions are for reporting errors (in C++; other languages can have different uses for exceptions).
18164 * Exceptions are not for errors that can be handled locally.
18165 * Don't try to catch every exception in every function (that's tedious, clumsy, and leads to slow code).
18166 * Exceptions are not for errors that require instant termination of a module/system after a non-recoverable error.
18168 ##### Example
18170     ???
18172 ##### Alternative
18174 * [RAII](#Re-raii)
18175 * Contracts/assertions: Use GSL's `Expects` and `Ensures` (until we get language support for contracts)
18177 ### <a name="Rnr-lots-of-files"></a>NR.4: Don't: Place each class declaration in its own source file
18179 ##### Reason (not to follow this rule)
18181 The resulting number of files are hard to manage and can slow down compilation.
18182 Individual classes are rarely a good logical unit of maintenance and distribution.
18184 ##### Example
18186     ???
18188 ##### Alternative
18190 * Use namespaces containing logically cohesive sets of classes and functions.
18192 ### <a name="Rnr-two-phase-init"></a>NR.5: Don't: Don't do substantive work in a constructor; instead use two-phase initialization
18194 ##### Reason (not to follow this rule)
18196 Following this rule leads to weaker invariants,
18197 more complicated code (having to deal with semi-constructed objects),
18198 and errors (when we didn't deal correctly with semi-constructed objects consistently).
18200 ##### Example
18202     ???
18204 ##### Alternative
18206 * Always establish a class invariant in a constructor.
18207 * Don't define an object before it is needed.
18209 ### <a name="Rnr-goto-exit"></a>NR.6: Don't: Place all cleanup actions at the end of a function and `goto exit`
18211 ##### Reason (not to follow this rule)
18213 `goto` is error-prone.
18214 This technique is a pre-exception technique for RAII-like resource and error handling.
18216 ##### Example, bad
18218     void do_something(int n)
18219     {
18220         if (n < 100) goto exit;
18221         // ...
18222         int* p = (int*) malloc(n);
18223         // ...
18224         if (some_ error) goto_exit;
18225         // ...
18226     exit:
18227         free(p);
18228     }
18230 and spot the bug.
18232 ##### Alternative
18234 * Use exceptions and [RAII](#Re-raii)
18235 * for non-RAII resources, use [`finally`](#Re-finally).
18237 ### <a name="Rnr-protected-data"></a>NR.7: Don't: Make all data members `protected`
18239 ##### Reason (not to follow this rule)
18241 `protected` data is a source of errors.
18242 `protected` data can be manipulated from an unbounded amount of code in various places.
18243 `protected` data is the class hierarchy equivalent to global data.
18245 ##### Example
18247     ???
18249 ##### Alternative
18251 * [Make member data `public` or (preferably) `private`](#Rh-protected)
18254 # <a name="S-references"></a>RF: References
18256 Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++.
18257 Many
18259 * focus on lower-level issues, such as the spelling of identifiers
18260 * are written by C++ novices
18261 * see "stopping programmers from doing unusual things" as their primary aim
18262 * aim at portability across many compilers (some 10 years old)
18263 * are written to preserve decades old code bases
18264 * aim at a single application domain
18265 * are downright counterproductive
18266 * are ignored (must be ignored by programmers to get their work done well)
18268 A bad coding standard is worse than no coding standard.
18269 However an appropriate set of guidelines are much better than no standards: "Form is liberating."
18271 Why can't we just have a language that allows all we want and disallows all we don't want ("a perfect language")?
18272 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.
18273 Also, your needs change over time and a general-purpose language is needed to allow you to adapt.
18274 A language that is ideal for today would be overly restrictive tomorrow.
18276 Coding guidelines adapt the use of a language to specific needs.
18277 Thus, there cannot be a single coding style for everybody.
18278 We expect different organizations to provide additions, typically with more restrictions and firmer style rules.
18280 Reference sections:
18282 * [RF.rules: Coding rules](#SS-rules)
18283 * [RF.books: Books with coding guidelines](#SS-books)
18284 * [RF.C++: C++ Programming (C++11/C++14)](#SS-Cplusplus)
18285 * [RF.web: Websites](#SS-web)
18286 * [RS.video: Videos about "modern C++"](#SS-vid)
18287 * [RF.man: Manuals](#SS-man)
18289 ## <a name="SS-rules"></a>RF.rules: Coding rules
18291 * [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html).
18292   ???.
18293 * [Bloomberg: BDE C++ Coding](https://github.com/bloomberg/bde/wiki/CodingStandards.pdf).
18294   Has a strong emphasis on code organization and layout.
18295 * Facebook: ???
18296 * [GCC Coding Conventions](https://gcc.gnu.org/codingconventions.html).
18297   C++03 and (reasonably) a bit backwards looking.
18298 * [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html).
18299   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.
18300 * [JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS](http://www.stroustrup.com/JSF-AV-rules.pdf).
18301   Document Number 2RDU00001 Rev C. December 2005.
18302   For flight control software.
18303   For hard real time.
18304   This means that it is necessarily very restrictive ("if the program fails somebody dies").
18305   For example, no free store allocation or deallocation may occur after the plane takes off (no memory overflow and no fragmentation allowed).
18306   No exception may be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
18307   Libraries used have to have been approved for mission critical applications.
18308   Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
18309   Recommended, but note its very specific focus.
18310 * [Mozilla Portability Guide](https://developer.mozilla.org/en-US/docs/Mozilla/C%2B%2B_Portability_Guide).
18311   As the name indicates, this aims for portability across many (old) compilers.
18312   As such, it is restrictive.
18313 * [Geosoft.no: C++ Programming Style Guidelines](http://geosoft.no/development/cppstyle.html).
18314   ???.
18315 * [Possibility.com: C++ Coding Standard](http://www.possibility.com/Cpp/CppCodingStandard.html).
18316   ???.
18317 * [SEI CERT: Secure C++ Coding Standard](https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637).
18318   A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
18319   Many of their rules apply generally.
18320 * [High Integrity C++ Coding Standard](http://www.codingstandard.com/).
18321 * [llvm](http://llvm.org/docs/CodingStandards.html).
18322   Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
18323 * ???
18325 ## <a name="SS-books"></a>RF.books: Books with coding guidelines
18327 * [Meyers96](#Meyers96) Scott Meyers: *More Effective C++*. Addison-Wesley 1996.
18328 * [Meyers97](#Meyers97) Scott Meyers: *Effective C++, Second Edition*. Addison-Wesley 1997.
18329 * [Meyers01](#Meyers01) Scott Meyers: *Effective STL*. Addison-Wesley 2001.
18330 * [Meyers05](#Meyers05) Scott Meyers: *Effective C++, Third Edition*. Addison-Wesley 2005.
18331 * [Meyers15](#Meyers15) Scott Meyers: *Effective Modern C++*. O'Reilly 2015.
18332 * [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.
18333 * [Stroustrup05](#Stroustrup05) Bjarne Stroustrup: [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
18334   LCSD05. October 2005.
18335 * [Stroustrup14](#Stroustrup05) Stroustrup: [A Tour of C++](http://www.stroustrup.com/Tour.html).
18336   Addison Wesley 2014.
18337   Each chapter ends with an advice section consisting of a set of recommendations.
18338 * [Stroustrup13](#Stroustrup13) Stroustrup: [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html).
18339   Addison Wesley 2013.
18340   Each chapter ends with an advice section consisting of a set of recommendations.
18341 * Stroustrup: [Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
18342   for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
18343   Mostly low-level naming and layout rules.
18344   Primarily a teaching tool.
18346 ## <a name="SS-Cplusplus"></a>RF.C++: C++ Programming (C++11/C++14)
18348 * [TC++PL4](http://www.stroustrup.com/4th.html):
18349 A thorough description of the C++ language and standard libraries for experienced programmers.
18350 * [Tour++](http://www.stroustrup.com/Tour.html):
18351 An overview of the C++ language and standard libraries for experienced programmers.
18352 * [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html):
18353 A textbook for beginners and relative novices.
18355 ## <a name="SS-web"></a>RF.web: Websites
18357 * [isocpp.org](https://isocpp.org)
18358 * [Bjarne Stroustrup's home pages](http://www.stroustrup.com)
18359 * [WG21](http://www.open-std.org/jtc1/sc22/wg21/)
18360 * [Boost](http://www.boost.org)<a name="Boost"></a>
18361 * [Adobe open source](http://www.adobe.com/open-source.html)
18362 * [Poco libraries](http://pocoproject.org/)
18363 * Sutter's Mill?
18364 * ???
18366 ## <a name="SS-vid"></a>RS.video: Videos about "modern C++"
18368 * Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012.
18369 * 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
18370 * All the talks from [CppCon '14](https://isocpp.org/blog/2014/11/cppcon-videos-c9)
18371 * Bjarne Stroustrup: [The essence of C++](https://www.youtube.com/watch?v=86xWVb4XIyE) at the University of Edinburgh. 2014.
18372 * Sutter: ???
18373 * CppCon 15
18374 * ??? C++ Next
18375 * ??? Meting C++
18376 * ??? more ???
18378 ## <a name="SS-man"></a>RF.man: Manuals
18380 * ISO C++ Standard C++11.
18381 * ISO C++ Standard C++14.
18382 * [ISO C++ Standard C++17 CD](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf). Committee Draft.
18383 * [Palo Alto "Concepts" TR](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3351.pdf).
18384 * [ISO C++ Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
18385 * [WG21 Ranges report](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf). Draft.
18387 ## <a name="SS-ack"></a>Acknowledgements
18389 Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.:
18391 * Peter Juhl
18392 * Neil MacIntosh
18393 * Axel Naumann
18394 * Andrew Pardoe
18395 * Gabriel Dos Reis
18396 * Zhuang, Jiangang (Jeff)
18397 * Sergey Zubkov
18399 and see the contributor list on the github.
18401 # <a name="S-profile"></a>Pro: Profiles
18403 Ideally, we would follow all of the guidelines.
18404 That would give the cleanest, most regular, least error-prone, and often the fastest code.
18405 Unfortunately, that is usually impossible because we have to fit our code into large code bases and use existing libraries.
18406 Often, such code has been written over decades and does not follow these guidelines.
18407 We must aim for [gradual adoption](#S-modernizing).
18409 Whatever strategy for gradual adoption we adopt, we need to be able to apply sets of related guidelines to address some set
18410 of problems first and leave the rest until later.
18411 A similar idea of "related guidelines" becomes important when some, but not all, guidelines are considered relevant to a code base
18412 or if a set of specialized guidelines is to be applied for a specialized application area.
18413 We call such a set of related guidelines a "profile".
18414 We aim for such a set of guidelines to be coherent so that they together help us reach a specific goal, such as "absence of range errors"
18415 or "static type safety."
18416 Each profile is designed to eliminate a class of errors.
18417 Enforcement of "random" rules in isolation is more likely to be disruptive to a code base than delivering a definite improvement.
18419 A "profile" is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee.
18420 "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be).
18421 "Portably enforceable" means they are like language rules, so programmers can count on different enforcement tools giving the same answer for the same code.
18423 Code written to be warning-free using such a language profile is considered to conform to the profile.
18424 Conforming code is considered to be safe by construction with regard to the safety properties targeted by that profile.
18425 Conforming code will not be the root cause of errors for that property,
18426 although such errors may be introduced into a program by other code, libraries or the external environment.
18427 A profile may also introduce additional library types to ease conformance and encourage correct code.
18429 Profiles summary:
18431 * [Pro.type: Type safety](#SS-type)
18432 * [Pro.bounds: Bounds safety](#SS-bounds)
18433 * [Pro.lifetime: Lifetime safety](#SS-lifetime)
18435 In the future, we expect to define many more profiles and add more checks to existing profiles.
18436 Candidates include:
18438 * narrowing arithmetic promotions/conversions (likely part of a separate safe-arithmetic profile)
18439 * arithmetic cast from negative floating point to unsigned integral type (ditto)
18440 * selected undefined behavior: Start with Gabriel Dos Reis's UB list developed for the WG21 study group
18441 * selected unspecified behavior: Addressing portability concerns.
18442 * `const` violations: Mostly done by compilers already, but we can catch inappropriate casting and underuse of `const`.
18444 Enabling a profile is implementation defined; typically, it is set in the analysis tool used.
18446 To suppress enforcement of a profile check, place a `suppress` annotation on a language contract. For example:
18448     [[suppress(bounds)]] char* raw_find(char* p, int n, char x)    // find x in p[0]..p[n-1]
18449     {
18450         // ...
18451     }
18453 Now `raw_find()` can scramble memory to its heart's content.
18454 Obviously, suppression should be very rare.
18456 ## <a name="SS-type"></a>Pro.safety: Type-safety profile
18458 This profile makes it easier to construct code that uses types correctly and avoids inadvertent type punning.
18459 It does so by focusing on removing the primary sources of type violations, including unsafe uses of casts and unions.
18461 For the purposes of this section,
18462 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.
18463 Memory accessed as a type `T` should not be valid memory that actually contains an object of an unrelated type `U`.
18464 Note that the safety is intended to be complete when combined also with [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
18466 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
18468 Type safety profile summary:
18470 * [Type.1: Don't use `reinterpret_cast`](#Pro-type-reinterpretcast)
18471 * [Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead](#Pro-type-downcast)
18472 * [Type.3: Don't use `const_cast` to cast away `const` (i.e., at all)](#Pro-type-constcast)
18473 * [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)
18474 * [Type.4.1: Don't use `T(expression)` for casting](#Pro-fct-style-cast)
18475 * [Type.5: Don't use a variable before it has been initialized](#Pro-type-init)
18476 * [Type.6: Always initialize a member variable](#Pro-type-memberinit)
18477 * [Type.7: Avoid accessing members of raw unions. Prefer `variant` instead](#Pro-fct-style-cast)
18478 * [Type.8: Avoid reading from varargs or passing vararg arguments. Prefer variadic template parameters instead](#Pro-type-varargs)
18480 ##### Impact
18482 With the type-safety profile you can trust that every operation is applied to a valid object.
18483 Exception may be thrown to indicate errors that cannot be detected statically (at compile time).
18484 Note that this type-safety can be complete only if we also have [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).
18485 Without those guarantees, a region of memory could be accessed independent of which object, objects, or parts of objects are stored in it.
18487 ### <a name="Pro-type-reinterpretcast"></a>Type.1: Don't use `reinterpret_cast`.
18489 ##### Reason
18491 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`.
18493 ##### Example, bad
18495     std::string s = "hello world";
18496     double* p = reinterpret_cast<double*>(&s); // BAD
18498 ##### Enforcement
18500 Issue a diagnostic for any use of `reinterpret_cast`. To fix: Consider using a `variant` instead.
18502 ### <a name="Pro-type-downcast"></a>Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead.
18504 ##### Reason
18506 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`.
18508 ##### Example, bad
18510     class Base { public: virtual ~Base() = 0; };
18512     class Derived1 : public Base { };
18514     class Derived2 : public Base {
18515         std::string s;
18516     public:
18517         std::string get_s() { return s; }
18518     };
18520     Derived1 d1;
18521     Base* p1 = &d1; // ok, implicit conversion to pointer to Base is fine
18523     // BAD, tries to treat d1 as a Derived2, which it is not
18524     Derived2* p2 = static_cast<Derived2*>(p1);
18525     // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1
18526     cout << p2->get_s();
18528 ##### Example, bad
18530     struct Foo { int a, b; };
18531     struct Foobar : Foo { int bar; };
18533     void use(int i, Foo& x)
18534     {
18535         if (0 < i) {
18536             Foobar& x1 = dynamic_cast<Foobar&>(x);  // error: Foo is not polymorphic
18537             Foobar& x2 = static_cast<Foobar&>(x);   // bad
18538             // ...
18539         }
18540         // ...
18541     }
18543     // ...
18545     use(99, *new Foo{1, 2});  // not a Foobar
18547 If a class hierarchy isn't polymorphic, avoid casting.
18548 It is entirely unsafe.
18549 Look for a better design.
18550 See also [C.146](#Rh-dynamic_cast).
18552 ##### Enforcement
18554 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.
18556 ### <a name="Pro-type-constcast"></a>Type.3: Don't use `const_cast` to cast away `const` (i.e., at all).
18558 ##### Reason
18560 Casting away `const` is a lie. If the variable is actually declared `const`, it's a lie punishable by undefined behavior.
18562 ##### Example, bad
18564     void f(const int& i)
18565     {
18566         const_cast<int&>(i) = 42;   // BAD
18567     }
18569     static int i = 0;
18570     static const int j = 0;
18572     f(i); // silent side effect
18573     f(j); // undefined behavior
18575 ##### Example
18577 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:
18579     class Bar;
18581     class Foo {
18582     public:
18583         // BAD, duplicates logic
18584         Bar& get_bar() {
18585             /* complex logic around getting a non-const reference to my_bar */
18586         }
18588         const Bar& get_bar() const {
18589             /* same complex logic around getting a const reference to my_bar */
18590         }
18591     private:
18592         Bar my_bar;
18593     };
18595 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`:
18597     class Foo {
18598     public:
18599         // not great, non-const calls const version but resorts to const_cast
18600         Bar& get_bar() {
18601             return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());
18602         }
18603         const Bar& get_bar() const {
18604             /* the complex logic around getting a const reference to my_bar */
18605         }
18606     private:
18607         Bar my_bar;
18608     };
18610 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.
18612 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:
18614     class Foo {
18615     public:                         // good
18616               Bar& get_bar()       { return get_bar_impl(*this); }
18617         const Bar& get_bar() const { return get_bar_impl(*this); }
18618     private:
18619         Bar my_bar;
18621         template<class T>           // good, deduces whether T is const or non-const
18622         static auto get_bar_impl(T& t) -> decltype(t.get_bar())
18623             { /* the complex logic around getting a possibly-const reference to my_bar */ }
18624     };
18626 ##### Exception
18628 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.
18630 ##### See also: 
18632 [ES.50, Don't cast away `const`](#Res-casts-const) for more discussion.
18634 ##### Enforcement
18636 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`.
18638 ### <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`.
18640 ##### Reason
18642 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`.
18643 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.
18645 ##### Example, bad
18647     std::string s = "hello world";
18648     double* p0 = (double*)(&s); // BAD
18650     class Base { public: virtual ~Base() = 0; };
18652     class Derived1 : public Base { };
18654     class Derived2 : public Base {
18655         std::string s;
18656     public:
18657         std::string get_s() { return s; }
18658     };
18660     Derived1 d1;
18661     Base* p1 = &d1; // ok, implicit conversion to pointer to Base is fine
18663     // BAD, tries to treat d1 as a Derived2, which it is not
18664     Derived2* p2 = (Derived2*)(p1);
18665     // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1
18666     cout << p2->get_s();
18668     void f(const int& i) {
18669         (int&)(i) = 42;   // BAD
18670     }
18672     static int i = 0;
18673     static const int j = 0;
18675     f(i); // silent side effect
18676     f(j); // undefined behavior
18678 ##### Enforcement
18680 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.
18682 ### <a name="Pro-fct-style-cast"></a>Type.4.1: Don't use `T(expression)` for casting.
18684 ##### Reason
18686 If `e` is of a built-in type, `T(e)` is equivalent to the error-prone `(T)e`.
18688 ##### Example, bad
18690     int* p = f(x);
18691     auto i = int(p);    // Potential damaging cast; don't or use `reinterpret_cast`
18693     short s = short(i); // potentially narrowing; don't or use `narrow` or `narrow_cast`
18695 ##### Note
18697 The {}-syntax makes the desire for construction explicit and doesn't allow narrowing
18699     f(Foo{bar});
18701 ##### Enforcement
18703 Flag `T(e)` if used for `e` of a built-in type.
18705 ### <a name="Pro-type-init"></a>Type.5: Don't use a variable before it has been initialized.
18707 [ES.20: Always initialize an object](#Res-always) is required.
18709 ### <a name="Pro-type-memberinit"></a>Type.6: Always initialize a member variable.
18711 ##### Reason
18713 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.
18715 ##### Example
18717     struct X { int i; };
18719     X x;
18720     use(x); // BAD, x has not been initialized
18722     X x2{}; // GOOD
18723     use(x2);
18725 ##### Enforcement
18727 * 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.
18728 * Issue a diagnostic when constructing an object of a trivially constructible type without `()` or `{}` to initialize its members. To fix: Add `()` or `{}`.
18730 ### <a name="Pro-type-unions"></a>Type.7: Avoid accessing members of raw unions. Prefer `variant` instead.
18732 ##### Reason
18734 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.
18736 ##### Example
18738     union U { int i; double d; };
18740     U u;
18741     u.i = 42;
18742     use(u.d); // BAD, undefined
18744     variant<int, double> u;
18745     u = 42; // u now contains int
18746     use(u.get<int>()); // ok
18747     use(u.get<double>()); // throws ??? update this when standardization finalizes the variant design
18749 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.
18751 ##### Enforcement
18753 * Issue a diagnostic for accessing a member of a union. To fix: Use a `variant` instead.
18755 ### <a name="Pro-type-varargs"></a>Type.8: Avoid reading from varargs or passing vararg arguments. Prefer variadic template parameters instead.
18757 ##### Reason
18759 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.
18761 ##### Example
18763     int sum(...) {
18764         // ...
18765         while (/*...*/)
18766             result += va_arg(list, int); // BAD, assumes it will be passed ints
18767         // ...
18768     }
18770     sum(3, 2); // ok
18771     sum(3.14159, 2.71828); // BAD, undefined
18773     template<class ...Args>
18774     auto sum(Args... args) { // GOOD, and much more flexible
18775         return (... + args); // note: C++17 "fold expression"
18776     }
18778     sum(3, 2); // ok: 5
18779     sum(3.14159, 2.71828); // ok: ~5.85987
18781 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.
18783 ##### Enforcement
18785 * Issue a diagnostic for using `va_list`, `va_start`, or `va_arg`. To fix: Use a variadic template parameter list instead.
18786 * 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)]]`.
18788 ## <a name="SS-bounds"></a>Pro.bounds: Bounds safety profile
18790 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.
18792 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.)
18794 The following are under consideration but not yet in the rules below, and may be better in other profiles:
18796 * ???
18798 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
18800 Bounds safety profile summary:
18802 * [Bounds.1: Don't use pointer arithmetic. Use `span` instead](#Pro-bounds-arithmetic)
18803 * [Bounds.2: Only index into arrays using constant expressions](#Pro-bounds-arrayindex)
18804 * [Bounds.3: No array-to-pointer decay](#Pro-bounds-decay)
18805 * [Bounds.4: Don't use standard library functions and types that are not bounds-checked](#Pro-bounds-stdlib)
18808 ### <a name="Pro-bounds-arithmetic"></a>Bounds.1: Don't use pointer arithmetic. Use `span` instead.
18810 ##### Reason
18812 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.
18814 ##### Example, bad
18816     void f(int* p, int count)
18817     {
18818         if (count < 2) return;
18820         int* q = p + 1; // BAD
18822         ptrdiff_t d;
18823         int n;
18824         d = (p - &n); // OK
18825         d = (q - p); // OK
18827         int n = *p++; // BAD
18829         if (count < 6) return;
18831         p[4] = 1; // BAD
18833         p[count - 1] = 2; // BAD
18835         use(&p[0], 3); // BAD
18836     }
18838 ##### Example, good
18840     void f(span<int> a) // BETTER: use span in the function declaration
18841     {
18842         if (a.length() < 2) return;
18844         int n = a[0]; // OK
18846         span<int> q = a.subspan(1); // OK
18848         if (a.length() < 6) return;
18850         a[4] = 1; // OK
18852         a[count - 1] = 2; // OK
18854         use(a.data(), 3); // OK
18855     }
18857 ##### Enforcement
18859 Issue a diagnostic for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
18861 ### <a name="Pro-bounds-arrayindex"></a>Bounds.2: Only index into arrays using constant expressions.
18863 ##### Reason
18865 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.
18867 ##### Example, bad
18869     void f(array<int, 10> a, int pos)
18870     {
18871         a[pos / 2] = 1; // BAD
18872         a[pos - 1] = 2; // BAD
18873         a[-1] = 3;    // BAD -- no replacement, just don't do this
18874         a[10] = 4;    // BAD -- no replacement, just don't do this
18875     }
18877 ##### Example, good
18879     // ALTERNATIVE A: Use a span
18881     // A1: Change parameter type to use span
18882     void f1(span<int, 10> a, int pos)
18883     {
18884         a[pos / 2] = 1; // OK
18885         a[pos - 1] = 2; // OK
18886     }
18888     // A2: Add local span and use that
18889     void f2(array<int, 10> arr, int pos)
18890     {
18891         span<int> a = {arr, pos}
18892         a[pos / 2] = 1; // OK
18893         a[pos - 1] = 2; // OK
18894     }
18896     // ALTERNATIVE B: Use at() for access
18897     void f3(array<int, 10> a, int pos)
18898     {
18899         at(a, pos / 2) = 1; // OK
18900         at(a, pos - 1) = 2; // OK
18901     }
18903 ##### Example, bad
18905     void f()
18906     {
18907         int arr[COUNT];
18908         for (int i = 0; i < COUNT; ++i)
18909             arr[i] = i; // BAD, cannot use non-constant indexer
18910     }
18912 ##### Example, good
18914     // ALTERNATIVE A: Use a span
18915     void f1()
18916     {
18917         int arr[COUNT];
18918         span<int> av = arr;
18919         for (int i = 0; i < COUNT; ++i)
18920             av[i] = i;
18921     }
18922     
18923     // ALTERNATIVE Aa: Use a span and range-for
18924     void f1a()
18925     {
18926          int arr[COUNT];
18927          span<int, COUNT> av = arr;
18928          int i = 0;
18929          for (auto& e : av)
18930              e = i++;
18931     }
18933     // ALTERNATIVE B: Use at() for access
18934     void f2()
18935     {
18936         int arr[COUNT];
18937         for (int i = 0; i < COUNT; ++i)
18938             at(arr, i) = i;
18939     }
18941 ##### Enforcement
18943 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.
18945 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.
18947 **Rewrite support**: Tooling can offer rewrites of array accesses that involve dynamic index expressions to use `at()` instead:
18949     static int a[10];
18951     void f(int i, int j)
18952     {
18953         a[i + j] = 12;      // BAD, could be rewritten as ...
18954         at(a, i + j) = 12;  // OK -- bounds-checked
18955     }
18957 ### <a name="Pro-bounds-decay"></a>Bounds.3: No array-to-pointer decay.
18959 ##### Reason
18961 Pointers should not be used as arrays. `span` is a bounds-checked, safe alternative to using pointers to access arrays.
18963 ##### Example, bad
18965     void g(int* p, size_t length);
18967     void f()
18968     {
18969         int a[5];
18970         g(a, 5);        // BAD
18971         g(&a[0], 1);    // OK
18972     }
18974 ##### Example, good
18976     void g(int* p, size_t length);
18977     void g1(span<int> av); // BETTER: get g() changed.
18979     void f()
18980     {
18981         int a[5];
18982         span<int> av = a;
18984         g(av.data(), av.length());   // OK, if you have no choice
18985         g1(a);                       // OK -- no decay here, instead use implicit span ctor
18986     }
18988 ##### Enforcement
18990 Issue a diagnostic for any expression that would rely on implicit conversion of an array type to a pointer type.
18992 ### <a name="Pro-bounds-stdlib"></a>Bounds.4: Don't use standard library functions and types that are not bounds-checked.
18994 ##### Reason
18996 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()`.
18998 ##### Example, bad
19000     void f()
19001     {
19002         array<int, 10> a, b;
19003         memset(a.data(), 0, 10);         // BAD, and contains a length error (length = 10 * sizeof(int))
19004         memcmp(a.data(), b.data(), 10);  // BAD, and contains a length error (length = 10 * sizeof(int))
19005     }
19007 Also, `std::array<>::fill()` or `std::fill()` or even an empty initializer are better candidate than `memset()`.
19009 ##### Example, good
19011     void f()
19012     {
19013         array<int, 10> a, b, c{};       // c is initialized to zero
19014         a.fill(0);
19015         fill(b.begin(), b.end(), 0);    // std::fill()
19016         fill(b, 0);                     // std::fill() + Ranges TS
19018         if ( a == b ) {
19019           // ...
19020         }
19021     }
19023 ##### Example
19025 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.
19027     void f(std::vector<int>& v, std::array<int, 12> a, int i)
19028     {
19029         v[0] = a[0];        // BAD
19030         v.at(0) = a[0];     // OK (alternative 1)
19031         at(v, 0) = a[0];    // OK (alternative 2)
19033         v.at(0) = a[i];     // BAD
19034         v.at(0) = a.at(i);  // OK (alternative 1)
19035         v.at(0) = at(a, i); // OK (alternative 2)
19036     }
19038 ##### Enforcement
19040 * Issue a diagnostic for any call to a standard library function that is not bounds-checked. ??? insert link to a list of banned functions
19042 **TODO Notes**:
19044 * Impact on the standard library will require close coordination with WG21, if only to ensure compatibility even if never standardized.
19045 * We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like `memcmp` and shipping them in the GSL.
19046 * 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).
19048 ## <a name="SS-lifetime"></a>Pro.lifetime: Lifetime safety profile
19050 See /docs folder for the initial design. The formal rules are in progress (as of March 2017).
19052 # <a name="S-gsl"></a>GSL: Guideline support library
19054 The GSL is a small library of facilities designed to support this set of guidelines.
19055 Without these facilities, the guidelines would have to be far more restrictive on language details.
19057 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.
19059 The GSL is header only, and can be found at [GSL: Guideline support library](https://github.com/Microsoft/GSL).
19060 The support library facilities are designed to be extremely lightweight (zero-overhead) so that they impose no overhead compared to using conventional alternatives.
19061 Where desirable, they can be "instrumented" with additional functionality (e.g., checks) for tasks such as debugging.
19063 These Guidelines assume a `variant` type, but this is not currently in GSL.
19064 Eventually, use [the one voted into C++17](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0088r3.html).
19066 Summary of GSL components:
19068 * [GSL.view: Views](#SS-views)
19069 * [GSL.owner](#SS-ownership)
19070 * [GSL.assert: Assertions](#SS-assertions)
19071 * [GSL.util: Utilities](#SS-utilities)
19072 * [GSL.concept: Concepts](#SS-gsl-concepts)
19074 We plan for a "ISO C++ standard style" semi-formal specification of the GSL.
19076 We rely on the ISO C++ standard library and hope for parts of the GSL to be absorbed into the standard library.
19078 ## <a name="SS-views"></a>GSL.view: Views
19080 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.
19082 These "views" are never owners.
19084 References are never owners. Note: References have many opportunities to outlive the objects they refer to (returning a local variable by reference, holding a reference to an element of a vector and doing `push_back`, binding to `std::max(x,y+1)`, etc. The Lifetime safety profile aims to address those things, but even so `owner<T&>` does not make sense and is discouraged.
19086 The names are mostly ISO standard-library style (lower case and underscore):
19088 * `T*`      // The `T*` is not an owner, may be null; assumed to be pointing to a single element.
19089 * `T&`      // The `T&` is not an owner and can never be a "null reference"; references are always bound to objects.
19091 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.
19092 Owners should be converted to resource handles (e.g., `unique_ptr` or `vector<T>`) or marked `owner<T*>`.
19094 * `owner<T*>`   // a `T*` that owns the object pointed/referred to; may be `nullptr`.
19096 `owner` is used to mark owning pointers in code that cannot be upgraded to use proper resource handles.
19097 Reasons for that include:
19099 * Cost of conversion.
19100 * The pointer is used with an ABI.
19101 * The pointer is part of the implementation of a resource handle.
19103 An `owner<T>` differs from a resource handle for a `T` by still requiring an explicit `delete`.
19105 An `owner<T>` is assumed to refer to an object on the free store (heap).
19107 If something is not supposed to be `nullptr`, say so:
19109 * `not_null<T>`   // `T` is usually a pointer type (e.g., `not_null<int*>` and `not_null<owner<Foo*>>`) that may not be `nullptr`.
19110   `T` can be any type for which `==nullptr` is meaningful.
19112 * `span<T>`       // `[`p`:`p+n`)`, constructor from `{p, q}` and `{p, n}`; `T` is the pointer type
19113 * `span_p<T>`     // `{p, predicate}` \[`p`:`q`) where `q` is the first element for which `predicate(*p)` is true
19114 * `string_span`   // `span<char>`
19115 * `cstring_span`  // `span<const char>`
19117 A `span<T>` refers to zero or more mutable `T`s unless `T` is a `const` type.
19119 "Pointer arithmetic" is best done within `span`s.
19120 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`.
19122 * `zstring`    // a `char*` supposed to be a C-style string; that is, a zero-terminated sequence of `char` or `nullptr`
19123 * `czstring`   // a `const char*` supposed to be a C-style string; that is, a zero-terminated sequence of `const` `char` or `nullptr`
19125 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.
19126 A sequence of characters that is not assumed to be zero-terminated should be a `char*`, rather than a `zstring`.
19127 French accent optional.
19129 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?
19131 ## <a name="SS-ownership"></a>GSL.owner: Ownership pointers
19133 * `unique_ptr<T>`     // unique ownership: `std::unique_ptr<T>`
19134 * `shared_ptr<T>`     // shared ownership: `std::shared_ptr<T>` (a counted pointer)
19135 * `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.
19136 * `dyn_array<T>`      // ??? needed ??? A heap-allocated array. The number of elements are determined at construction and fixed thereafter.
19137   The elements are mutable unless `T` is a `const` type. Basically a `span` that allocates and owns its elements.
19139 ## <a name="SS-assertions"></a>GSL.assert: Assertions
19141 * `Expects`     // precondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
19142                 // `Expects(p)` terminates the program unless `p == true`
19143                 // `Expect` in under control of some options (enforcement, error message, alternatives to terminate)
19144 * `Ensures`     // postcondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
19146 These assertions are currently macros (yuck!) and must appear in function definitions (only)
19147 pending standard committee decisions on contracts and assertion syntax.
19148 See [the contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf); using the attribute syntax,
19149 for example, `Expects(p!=nullptr)` will become `[[expects: p!=nullptr]]`.
19151 ## <a name="SS-utilities"></a>GSL.util: Utilities
19153 * `finally`       // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f`
19154 * `narrow_cast`   // `narrow_cast<T>(x)` is `static_cast<T>(x)`
19155 * `narrow`        // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
19156 * `[[implicit]]`  // "Marker" to put on single-argument constructors to explicitly make them non-explicit.
19157 * `move_owner`    // `p = move_owner(q)` means `p = q` but ???
19159 ## <a name="SS-gsl-concepts"></a>GSL.concept: Concepts
19161 These concepts (type predicates) are borrowed from
19162 Andrew Sutton's Origin library,
19163 the Range proposal,
19164 and the ISO WG21 Palo Alto TR.
19165 They are likely to be very similar to what will become part of the ISO C++ standard.
19166 The notation is that of the ISO WG21 [Concepts TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4553.pdf).
19167 Most of the concepts below are defined in [the Ranges TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4569.pdf).
19169 * `Range`
19170 * `String`   // ???
19171 * `Number`   // ???
19172 * `Sortable`
19173 * `Pointer`  // A type with `*`, `->`, `==`, and default construction (default construction is assumed to set the singular "null" value); see [smart pointers](#SS-gsl-smartptrconcepts)
19174 * `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](#SS-gsl-smartptrconcepts)
19175 * `Shared_ptr`   // A type that matches `Pointer`, has copy, and matches the Lifetime profile criteria for a `shared` owner type; see [smart pointers](#SS-gsl-smartptrconcepts)
19176 * `EqualityComparable`   // ???Must we suffer CaMelcAse???
19177 * `Convertible`
19178 * `Common`
19179 * `Boolean`
19180 * `Integral`
19181 * `SignedIntegral`
19182 * `SemiRegular` // ??? Copyable?
19183 * `Regular`
19184 * `TotallyOrdered`
19185 * `Function`
19186 * `RegularFunction`
19187 * `Predicate`
19188 * `Relation`
19189 * ...
19191 ### <a name="SS-gsl-smartptrconcepts"></a>Smart pointer concepts
19193 Described in [Lifetimes paper](https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetimes%20I%20and%20II%20-%20v0.9.1.pdf).
19195 # <a name="S-naming"></a>NL: Naming and layout rules
19197 Consistent naming and layout are helpful.
19198 If for no other reason because it minimizes "my style is better than your style" arguments.
19199 However, there are many, many, different styles around and people are passionate about them (pro and con).
19200 Also, most real-world projects includes code from many sources, so standardizing on a single style for all code is often impossible.
19201 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.
19202 IDEs and tools can help (as well as hinder).
19204 Naming and layout rules:
19206 * [NL.1: Don't say in comments what can be clearly stated in code](#Rl-comments)
19207 * [NL.2: State intent in comments](#Rl-comments-intent)
19208 * [NL.3: Keep comments crisp](#Rl-comments-crisp)
19209 * [NL.4: Maintain a consistent indentation style](#Rl-indent)
19210 * [NL.5: Don't encode type information in names](#Rl-name-type)
19211 * [NL.7: Make the length of a name roughly proportional to the length of its scope](#Rl-name-length)
19212 * [NL.8: Use a consistent naming style](#Rl-name)
19213 * [NL.9: Use `ALL_CAPS` for macro names only](#Rl-all-caps)
19214 * [NL.10: Avoid CamelCase](#Rl-camel)
19215 * [NL.11: Make literals readable](#Rl-literals)
19216 * [NL.15: Use spaces sparingly](#Rl-space)
19217 * [NL.16: Use a conventional class member declaration order](#Rl-order)
19218 * [NL.17: Use K&R-derived layout](#Rl-knr)
19219 * [NL.18: Use C++-style declarator layout](#Rl-ptr)
19220 * [NL.19: Avoid names that are easily misread](#Rl-misread)
19221 * [NL.20: Don't place two statements on the same line](#Rl-stmt)
19222 * [NL.21: Declare one name (only) per declaration](#Rl-dcl)
19223 * [NL.25: Don't use `void` as an argument type](#Rl-void)
19224 * [NL.26: Use conventional `const` notation](#Rl-const)
19226 Most of these rules are aesthetic and programmers hold strong opinions.
19227 IDEs also tend to have defaults and a range of alternatives.
19228 These rules are suggested defaults to follow unless you have reasons not to.
19230 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.
19231 We are not "legislating" (see the previous paragraph).
19232 However, we have had many requests for a set of naming and layout conventions to use when there are no external constraints.
19234 More specific and detailed rules are easier to enforce.
19236 These rules bear a strong resemblance to the recommendations in the [PPP Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
19237 written in support of Stroustrup's [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
19239 ### <a name="Rl-comments"></a>NL.1: Don't say in comments what can be clearly stated in code
19241 ##### Reason
19243 Compilers do not read comments.
19244 Comments are less precise than code.
19245 Comments are not updated as consistently as code.
19247 ##### Example, bad
19249     auto x = m * v1 + vv;   // multiply m with v1 and add the result to vv
19251 ##### Enforcement
19253 Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++.
19255 ### <a name="Rl-comments-intent"></a>NL.2: State intent in comments
19257 ##### Reason
19259 Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation.
19261 ##### Example
19263     void stable_sort(Sortable& c)
19264         // sort c in the order determined by <, keep equal elements (as defined by ==) in
19265         // their original relative order
19266     {
19267         // ... quite a few lines of non-trivial code ...
19268     }
19270 ##### Note
19272 If the comment and the code disagrees, both are likely to be wrong.
19274 ### <a name="Rl-comments-crisp"></a>NL.3: Keep comments crisp
19276 ##### Reason
19278 Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file.
19280 ##### Note
19282 Use intelligible English.
19283 I may be fluent in Danish, but most programmers are not; the maintainers of my code may not be.
19284 Avoid SMS lingo and watch your grammar, punctuation, and capitalization.
19285 Aim for professionalism, not "cool."
19287 ##### Enforcement
19289 not possible.
19291 ### <a name="Rl-indent"></a>NL.4: Maintain a consistent indentation style
19293 ##### Reason
19295 Readability. Avoidance of "silly mistakes."
19297 ##### Example, bad
19299     int i;
19300     for (i = 0; i < max; ++i); // bug waiting to happen
19301     if (i == j)
19302         return i;
19304 ##### Note
19306 Always indenting the statement after `if (...)`, `for (...)`, and `while (...)` is usually a good idea:
19308     if (i < 0) error("negative argument");
19310     if (i < 0)
19311         error("negative argument");
19313 ##### Enforcement
19315 Use a tool.
19317 ### <a name="Rl-name-type"></a>NL.5 Don't encode type information in names
19319 ##### Rationale
19321 If names reflect types rather than functionality, it becomes hard to change the types used to provide that functionality.
19322 Also, if the type of a variable is changed, code using it will have to be modified.
19323 Minimize unintentional conversions.
19325 ##### Example, bad
19327     void print_int(int i);
19328     void print_string(const char*);
19330     print_int(1);   // OK
19331     print_int(x);   // conversion to int if x is a double
19333 ##### Note
19335 Names with types encoded are either verbose or cryptic.
19337     printS  // print a std::string
19338     prints  // print a C-style string
19339     printi  // print an int
19341 PS. Hungarian notation is evil (at least in a strongly statically-typed language).
19343 ##### Note
19345 Some styles distinguishes members from local variable, and/or from global variable.
19347     struct S {
19348         int m_;
19349         S(int m) :m_{abs(m)} { }
19350     };
19352 This is not evil.
19354 ##### Note
19356 Like C++, some styles distinguishes types from non-types.
19357 For example, by capitalizing type names, but not the names of functions and variables.
19359     typename<typename T>
19360     class Hash_tbl {   // maps string to T
19361         // ...
19362     };
19364     Hash_tbl<int> index;
19366 This is not evil.
19368 ### <a name="Rl-name-length"></a>NL.7: Make the length of a name roughly proportional to the length of its scope
19370 **Rationale**: The larger the scope the greater the chance of confusion and of an unintended name clash.
19372 ##### Example
19374     double sqrt(double x);   // return the square root of x; x must be non-negative
19376     int length(const char* p);  // return the number of characters in a zero-terminated C-style string
19378     int length_of_string(const char zero_terminated_array_of_char[])    // bad: verbose
19380     int g;      // bad: global variable with a cryptic name
19382     int open;   // bad: global variable with a short, popular name
19384 The use of `p` for pointer and `x` for a floating-point variable is conventional and non-confusing in a restricted scope.
19386 ##### Enforcement
19390 ### <a name="Rl-name"></a>NL.8: Use a consistent naming style
19392 **Rationale**: Consistence in naming and naming style increases readability.
19394 ##### Note
19396 There are many styles and when you use multiple libraries, you can't follow all their different conventions.
19397 Choose a "house style", but leave "imported" libraries with their original style.
19399 ##### Example
19401 ISO Standard, use lower case only and digits, separate words with underscores:
19403 * `int`
19404 * `vector`
19405 * `my_map`
19407 Avoid double underscores `__`.
19409 ##### Example
19411 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
19412 ISO Standard, but with upper case used for your own types and concepts:
19414 * `int`
19415 * `vector`
19416 * `My_map`
19418 ##### Example
19420 CamelCase: capitalize each word in a multi-word identifier:
19422 * `int`
19423 * `vector`
19424 * `MyMap`
19425 * `myMap`
19427 Some conventions capitalize the first letter, some don't.
19429 ##### Note
19431 Try to be consistent in your use of acronyms and lengths of identifiers:
19433     int mtbf {12};
19434     int mean_time_between_failures {12}; // make up your mind
19436 ##### Enforcement
19438 Would be possible except for the use of libraries with varying conventions.
19440 ### <a name="Rl-all-caps"></a>NL.9: Use `ALL_CAPS` for macro names only
19442 ##### Reason
19444 To avoid confusing macros with names that obey scope and type rules.
19446 ##### Example
19448     void f()
19449     {
19450         const int SIZE{1000};  // Bad, use 'size' instead
19451         int v[SIZE];
19452     }
19454 ##### Note
19456 This rule applies to non-macro symbolic constants:
19458     enum bad { BAD, WORSE, HORRIBLE }; // BAD
19460 ##### Enforcement
19462 * Flag macros with lower-case letters
19463 * Flag `ALL_CAPS` non-macro names
19465 ### <a name="Rl-camel"></a>NL.10: Avoid CamelCase
19467 ##### Reason
19469 The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ standard library.
19470 If you prefer CamelCase, you have to choose among different flavors of camelCase.
19472 ##### Note
19474 This rule is a default to use only if you have a choice.
19475 Often, you don't have a choice and must follow an established style for [consistency](#Rl-name).
19476 The need for consistency beats personal taste.
19478 ##### Example
19480 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
19481 ISO Standard, but with upper case used for your own types and concepts:
19483 * `int`
19484 * `vector`
19485 * `My_map`
19487 ##### Enforcement
19489 Impossible.
19491 ### <a name="Rl-space"></a>NL.15: Use spaces sparingly
19493 ##### Reason
19495 Too much space makes the text larger and distracts.
19497 ##### Example, bad
19499     #include < map >
19501     int main(int argc, char * argv [ ])
19502     {
19503         // ...
19504     }
19506 ##### Example
19508     #include <map>
19510     int main(int argc, char* argv[])
19511     {
19512         // ...
19513     }
19515 ##### Note
19517 Some IDEs have their own opinions and add distracting space.
19519 ##### Note
19521 We value well-placed whitespace as a significant help for readability. Just don't overdo it.
19523 ### <a name="Rl-literals"></a>NL.11: Make literals readable
19525 ##### Reason
19527 Readability.
19529 ###### Example
19531 Use digit separators to avoid long strings of digits
19533     auto c = 299'792'458; // m/s2
19534     auto q2 = 0b0000'1111'0000'0000;
19535     auto ss_number = 123'456'7890;
19537 ###### Example
19539 Use literal suffixes where clarification is needed
19541     auto hello = "Hello!"s; // a std::string
19542     auto world = "world";   // a C-style string
19543     auto interval = 100ms;  // using <chrono>
19545 ###### Note
19547 Literals should not be sprinkled all over the code as ["magic constants"](#Res-magic),
19548 but it is still a good idea to make them readable where they are defined.
19549 It is easy to make a typo in a long string of integers.
19551 ###### Enforcement
19553 Flag long digit sequences. The trouble is to define "long"; maybe 7.
19555 ### <a name="Rl-order"></a>NL.16: Use a conventional class member declaration order
19557 ##### Reason
19559 A conventional order of members improves readability.
19561 When declaring a class use the following order
19563 * types: classes, enums, and aliases (`using`)
19564 * constructors, assignments, destructor
19565 * functions
19566 * data
19568 Use the `public` before `protected` before `private` order.
19570 Private types and functions can be placed with private data.
19572 Avoid multiple blocks of declarations of one access (e.g., `public`) dispersed among blocks of declarations with different access (e.g. `private`).
19574 ##### Example
19576     class X {
19577     public:
19578         // interface
19579     protected:
19580         // unchecked function for use by derived class implementations
19581     private:
19582         // implementation details
19583     };
19585 ##### Note
19587 The use of macros to declare groups of members often violates any ordering rules.
19588 However, macros obscures what is being expressed anyway.
19590 ##### Enforcement
19592 Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.
19594 ### <a name="Rl-knr"></a>NL.17: Use K&R-derived layout
19596 ##### Reason
19598 This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes) well.
19600 ##### Note
19602 In the context of C++, this style is often called "Stroustrup".
19604 ##### Example
19606     struct Cable {
19607         int x;
19608         // ...
19609     };
19611     double foo(int x)
19612     {
19613         if (0 < x) {
19614             // ...
19615         }
19617         switch (x) {
19618             case 0:
19619                 // ...
19620                 break;
19621             case amazing:
19622                 // ...
19623                 break;
19624             default:
19625                 // ...
19626                 break;
19627         }
19629         if (0 < x)
19630             ++x;
19632         if (x < 0)
19633             something();
19634         else
19635             something_else();
19637         return some_value;
19638     }
19640 Note the space between `if` and `(`
19642 ##### Note
19644 Use separate lines for each statement, the branches of an `if`, and the body of a `for`.
19646 ##### Note
19648 The `{` for a `class` and a `struct` in *not* on a separate line, but the `{` for a function is.
19650 ##### Note
19652 Capitalize the names of your user-defined types to distinguish them from standards-library types.
19654 ##### Note
19656 Do not capitalize function names.
19658 ##### Enforcement
19660 If you want enforcement, use an IDE to reformat.
19662 ### <a name="Rl-ptr"></a>NL.18: Use C++-style declarator layout
19664 ##### Reason
19666 The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types.
19667 The use in expressions argument doesn't hold for references.
19669 ##### Example
19671     T& operator[](size_t);   // OK
19672     T &operator[](size_t);   // just strange
19673     T & operator[](size_t);   // undecided
19675 ##### Enforcement
19677 Impossible in the face of history.
19680 ### <a name="Rl-misread"></a>NL.19: Avoid names that are easily misread
19682 ##### Reason
19684 Readability.
19685 Not everyone has screens and printers that make it easy to distinguish all characters.
19686 We easily confuse similarly spelled and slightly misspelled words.
19688 ##### Example
19690     int oO01lL = 6; // bad
19692     int splunk = 7;
19693     int splonk = 8; // bad: splunk and splonk are easily confused
19695 ##### Enforcement
19699 ### <a name="Rl-stmt"></a>NL.20: Don't place two statements on the same line
19701 ##### Reason
19703 Readability.
19704 It is really easy to overlook a statement when there is more on a line.
19706 ##### Example
19708     int x = 7; char* p = 29;    // don't
19709     int x = 7; f(x);  ++x;      // don't
19711 ##### Enforcement
19713 Easy.
19715 ### <a name="Rl-dcl"></a>NL.21: Declare one name (only) per declaration
19717 ##### Reason
19719 Readability.
19720 Minimizing confusion with the declarator syntax.
19722 ##### Note
19724 For details, see [ES.10](#Res-name-one).
19727 ### <a name="Rl-void"></a>NL.25: Don't use `void` as an argument type
19729 ##### Reason
19731 It's verbose and only needed where C compatibility matters.
19733 ##### Example
19735     void f(void);   // bad
19737     void g();       // better
19739 ##### Note
19741 Even Dennis Ritchie deemed `void f(void)` an abomination.
19742 You can make an argument for that abomination in C when function prototypes were rare so that banning:
19744     int f();
19745     f(1, 2, "weird but valid C89");   // hope that f() is defined int f(a, b, c) char* c; { /* ... */ }
19747 would have caused major problems, but not in the 21st century and in C++.
19749 ### <a name="Rl-const"></a>NL.26: Use conventional `const` notation
19751 ##### Reason
19753 Conventional notation is more familiar to more programmers.
19754 Consistency in large code bases.
19756 ##### Example
19758     const int x = 7;    // OK
19759     int const y = 9;    // bad
19761     const int *const p = nullptr;   // OK, constant pointer to constant int
19762     int const *const p = nullptr;   // bad, constant pointer to constant int
19764 ##### Note
19766 We are well aware that you could claim the "bad" examples more logical than the ones marked "OK",
19767 but they also confuse more people, especially novices relying on teaching material using the far more common, conventional OK style.
19769 As ever, remember that the aim of these naming and layout rules is consistency and that aesthetics vary immensely.
19771 ##### Enforcement
19773 Flag `const` used as a suffix for a type.
19775 # <a name="S-faq"></a>FAQ: Answers to frequently asked questions
19777 This section covers answers to frequently asked questions about these guidelines.
19779 ### <a name="Faq-aims"></a>FAQ.1: What do these guidelines aim to achieve?
19781 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.
19783 ### <a name="Faq-announced"></a>FAQ.2: When and where was this work first announced?
19785 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).
19787 ### <a name="Faq-maintainers"></a>FAQ.3: Who are the authors and maintainers of these guidelines?
19789 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!"
19791 ### <a name="Faq-contribute"></a>FAQ.4: How can I contribute?
19793 See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
19795 ### <a name="Faq-maintainer"></a>FAQ.5: How can I become an editor/maintainer?
19797 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!
19799 ### <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?
19801 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.
19803 ### <a name="Faq-isocpp"></a>FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`?
19805 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.
19807 ### <a name="Faq-cpp98"></a>FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version?
19809 No. These guidelines are about how to best use Standard C++14 (and, if you have an implementation available, the Concepts Technical Specification) and write code assuming you have a modern conforming compiler.
19811 ### <a name="Faq-language-extensions"></a>FAQ.9: Do these guidelines propose new language features?
19813 No. These guidelines are about how to best use Standard C++14 + the Concepts Technical Specification, and they limit themselves to recommending only those features.
19815 ### <a name="Faq-markdown"></a>FAQ.10: What version of Markdown do these guidelines use?
19817 These coding standards are written using [CommonMark](http://commonmark.org), and `<a>` HTML anchors.
19819 We are considering the following extensions from [GitHub Flavored Markdown (GFM)](https://help.github.com/articles/github-flavored-markdown/):
19821 * fenced code blocks (consistently using indented vs. fenced is under discussion)
19822 * tables (none yet but we'll likely need them, and this is a GFM extension)
19824 Avoid other HTML tags and other extensions.
19826 Note: We are not yet consistent with this style.
19828 ### <a name="Faq-gsl"></a>FAQ.50: What is the GSL (guideline support library)?
19830 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.
19832 ### <a name="Faq-msgsl"></a>FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL?
19834 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.
19836 ### <a name="Faq-gsl-implementation"></a>FAQ.52: Why not supply an actual GSL implementation in/with these guidelines?
19838 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.
19840 ### <a name="Faq-boost"></a>FAQ.53: Why weren't the GSL types proposed through Boost?
19842 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.
19844 ### <a name="Faq-gsl-iso"></a>FAQ.54: Has the GSL (guideline support library) been approved by the ISO C++ standards committee?
19846 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.
19848 ### <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`?
19850 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.
19852 ### <a name="Faq-gsl-owner"></a>FAQ.56: Is `owner` the same as the proposed `observer_ptr`?
19854 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.
19856 ### <a name="Faq-gsl-stack-array"></a>FAQ.57: Is `stack_array` the same as the standard `array`?
19858 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.
19860 ### <a name="Faq-gsl-dyn-array"></a>FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`?
19862 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.
19864 ### <a name="Faq-gsl-expects"></a>FAQ.59: Is `Expects` the same as `assert`?
19866 No. It is a placeholder for language support for contract preconditions.
19868 ### <a name="Faq-gsl-ensures"></a>FAQ.60: Is `Ensures` the same as `assert`?
19870 No. It is a placeholder for language support for contract postconditions.
19872 # <a name="S-libraries"></a>Appendix A: Libraries
19874 This section lists recommended libraries, and explicitly recommends a few.
19876 ??? Suitable for the general guide? I think not ???
19878 # <a name="S-modernizing"></a>Appendix B: Modernizing code
19880 Ideally, we follow all rules in all code.
19881 Realistically, we have to deal with a lot of old code:
19883 * application code written before the guidelines were formulated or known
19884 * libraries written to older/different standards
19885 * code written under "unusual" constraints
19886 * code that we just haven't gotten around to modernizing
19888 If we have a million lines of new code, the idea of "just changing it all at once" is typically unrealistic.
19889 Thus, we need a way of gradually modernizing a code base.
19891 Upgrading older code to modern style can be a daunting task.
19892 Often, the old code is both a mess (hard to understand) and working correctly (for the current range of uses).
19893 Typically, the original programmer is not around and the test cases incomplete.
19894 The fact that the code is a mess dramatically increases the effort needed to make any change and the risk of introducing errors.
19895 Often, messy old code runs unnecessarily slowly because it requires outdated compilers and cannot take advantage of modern hardware.
19896 In many cases, automated "modernizer"-style tool support would be required for major upgrade efforts.
19898 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.
19899 Making code "look pretty" or "follow modern style" are not by themselves reasons for change.
19900 There are risks implied by every change and costs (including the cost of lost opportunities) implied by having an outdated code base.
19901 The cost reductions must outweigh the risks.
19903 But how?
19905 There is no one approach to modernizing code.
19906 How best to do it depends on the code, the pressure for updates, the backgrounds of the developers, and the available tool.
19907 Here are some (very general) ideas:
19909 * The ideal is "just upgrade everything." That gives the most benefits for the shortest total time.
19910   In most circumstances, it is also impossible.
19911 * 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.
19912 * 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.
19913 * We could start by focusing on the interfaces, e.g., make sure that no resources are lost and no pointer is misused.
19914   This would be a set of changes across the whole code base, but would most likely have huge benefits.
19915   Afterwards, code hidden behind those interfaces can be gradually modernized without affecting other code.
19917 Whichever way you choose, please note that the most advantages come with the highest conformance to the guidelines.
19918 The guidelines are not a random set of unrelated rules where you can randomly pick and choose with an expectation of success.
19920 We would dearly love to hear about experience and about tools used.
19921 Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools.
19923 # <a name="S-discussion"></a>Appendix C: Discussion
19925 This section contains follow-up material on rules and sets of rules.
19926 In particular, here we present further rationale, longer examples, and discussions of alternatives.
19928 ### <a name="Sd-order"></a>Discussion: Define and initialize member variables in the order of member declaration
19930 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.
19932     class Employee {
19933         string email, first, last;
19934     public:
19935         Employee(const char* firstName, const char* lastName);
19936         // ...
19937     };
19939     Employee::Employee(const char* firstName, const char* lastName)
19940       : first(firstName),
19941         last(lastName),
19942         // BAD: first and last not yet constructed
19943         email(first + "." + last + "@acme.com")
19944     {}
19946 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.
19948 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.
19950 **References**:
19952 [\[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
19954 ### <a name="TBD"></a>Use of `=`, `{}`, and `()` as initializers
19958 ### <a name="Sd-factory"></a>Discussion: Use a factory function if you need "virtual behavior" during initialization
19960 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:
19962 * *Pass the buck:* Just document that user code must call the post-initialization function right after constructing an object.
19963 * *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.
19964 * *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).)
19965 * *Use a factory function:* This way, you can easily force a mandatory invocation of a post-constructor function.
19967 Here is an example of the last option:
19969     class B {
19970     public:
19971         B() { /* ... */ f(); /* ... */ }   // BAD: see Item 49.1
19973         virtual void f() = 0;
19975         // ...
19976     };
19978     class B {
19979     protected:
19980         B() { /* ... */ }
19981         virtual void PostInitialize()    // called right after construction
19982             { /* ... */ f(); /* ... */ }   // GOOD: virtual dispatch is safe
19983     public:
19984         virtual void f() = 0;
19986         template<class T>
19987         static shared_ptr<T> Create()    // interface for creating objects
19988         {
19989             auto p = make_shared<T>();
19990             p->PostInitialize();
19991             return p;
19992         }
19993     };
19996     class D : public B {                 // some derived class
19997     public:
19998         void f() override { /* ...  */ };
20000     protected:
20001         D() {}
20003         template<class T>
20004         friend shared_ptr<T> B::Create();
20005     };
20007     shared_ptr<D> p = D::Create<D>();    // creating a D object
20009 This design requires the following discipline:
20011 * Derived classes such as `D` must not expose a public constructor. Otherwise, `D`'s users could create `D` objects that don't invoke `PostInitialize`.
20012 * Allocation is limited to `operator new`. `B` can, however, override `new` (see Items 45 and 46).
20013 * `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.
20015 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.
20017 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).
20019 **References**: [\[Alexandrescu01\]](#Alexandrescu01) §3, [\[Boost\]](#Boost), [\[Dewhurst03\]](#Dewhurst03) §75, [\[Meyers97\]](#Meyers97) §46, [\[Stroustrup00\]](#Stroustrup00) §15.4.3, [\[Taligent94\]](#Taligent94)
20021 ### <a name="Sd-dtor"></a>Discussion: Make base class destructors public and virtual, or protected and nonvirtual
20023 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.
20025 ##### Example
20027 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>`:
20029     class Base {
20030     public:
20031         ~Base();                   // BAD, not virtual
20032         virtual ~Base();           // GOOD
20033         // ...
20034     };
20036     class Derived : public Base { /* ... */ };
20038     {
20039         unique_ptr<Base> pb = make_unique<Derived>();
20040         // ...
20041     } // ~pb invokes correct destructor only when ~Base is virtual
20043 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:
20045     class My_policy {
20046     public:
20047         virtual ~My_policy();      // BAD, public and virtual
20048     protected:
20049         ~My_policy();              // GOOD
20050         // ...
20051     };
20053     template<class Policy>
20054     class customizable : Policy { /* ... */ }; // note: private inheritance
20056 ##### Note
20058 This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles.
20060 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.
20062 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:
20064 * Whether it should behave virtually or not.
20065 * Whether it should be publicly available to all callers using a pointer to `Base` or else be a hidden internal implementation detail.
20067 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.
20069 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.
20071 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.)
20073 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.
20075 ##### Exception
20077 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.
20079 Consider also this rare case:
20081 * `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.
20082 * 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.
20084 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.
20086 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`.
20088 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.
20090 **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
20092 ### <a name="Sd-noexcept"></a>Discussion: Usage of noexcept
20096 ### <a name="Sd-never-fail"></a>Discussion: Destructors, deallocation, and swap must never fail
20098 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.
20100 ##### Example
20102     class Nefarious {
20103     public:
20104         Nefarious()  { /* code that could throw */ }   // ok
20105         ~Nefarious() { /* code that could throw */ }   // BAD, should not throw
20106         // ...
20107     };
20109 1. `Nefarious` objects are hard to use safely even as local variables:
20112         void test(string& s)
20113         {
20114             Nefarious n;          // trouble brewing
20115             string copy = s;      // copy the string
20116         } // destroy copy and then n
20118     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.
20120 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:
20123         class Innocent_bystander {
20124             Nefarious member;     // oops, poisons the enclosing class's destructor
20125             // ...
20126         };
20128         void test(string& s)
20129         {
20130             Innocent_bystander i; // more trouble brewing
20131             string copy2 = s;      // copy the string
20132         } // destroy copy and then i
20134     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`.
20136 3. You can't reliably create global or static `Nefarious` objects either:
20139         static Nefarious n;       // oops, any destructor exception can't be caught
20141 4. You can't reliably create arrays of `Nefarious`:
20144         void test()
20145         {
20146             std::array<Nefarious, 10> arr; // this line can std::terminate(!)
20147         }
20149     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.
20151 5. You can't use `Nefarious` objects in standard containers:
20154         std::vector<Nefarious> vec(10);   // this line can std::terminate()
20156     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.
20158 ##### Note
20160 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.
20162 Consider the following advice and requirements found in the C++ Standard:
20164 > 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)
20166 > 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)
20168 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.
20169 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`:
20171     T& T::operator=(const T& other) {
20172         auto temp = other;
20173         swap(temp);
20174     }
20176 (See also Item 56. ???)
20178 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).
20180 When using exceptions as your error handling mechanism, always document this behavior by declaring these functions `noexcept`. (See Item 75.)
20182 **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
20184 ## <a name="Sd-consistent"></a>Define Copy, move, and destroy consistently
20186 ##### Reason
20188  ???
20190 ##### Note
20192 If you define a copy constructor, you must also define a copy assignment operator.
20194 ##### Note
20196 If you define a move constructor, you must also define a move assignment operator.
20198 ##### Example
20200     class X {
20201         // ...
20202     public:
20203         X(const X&) { /* stuff */ }
20205         // BAD: failed to also define a copy assignment operator
20207         X(x&&) { /* stuff */ }
20209         // BAD: failed to also define a move assignment operator
20210     };
20212     X x1;
20213     X x2 = x1; // ok
20214     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
20216 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.
20218     class X {
20219         HANDLE hnd;
20220         // ...
20221     public:
20222         ~X() { /* custom stuff, such as closing hnd */ }
20223         // suspicious: no mention of copying or moving -- what happens to hnd?
20224     };
20226     X x1;
20227     X x2 = x1; // pitfall: either fails to compile, or does something suspicious
20228     x2 = x1;   // pitfall: either fails to compile, or does something suspicious
20230 If you define copying, and any base or member has a type that defines a move operation, you should also define a move operation.
20232     class X {
20233         string s; // defines more efficient move operations
20234         // ... other data members ...
20235     public:
20236         X(const X&) { /* stuff */ }
20237         X& operator=(const X&) { /* stuff */ }
20239         // BAD: failed to also define a move construction and move assignment
20240         // (why wasn't the custom "stuff" repeated here?)
20241     };
20243     X test()
20244     {
20245         X local;
20246         // ...
20247         return local;  // pitfall: will be inefficient and/or do the wrong thing
20248     }
20250 If you define any of the copy constructor, copy assignment operator, or destructor, you probably should define the others.
20252 ##### Note
20254 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:
20256 * 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.)
20257 * 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.
20258 * 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.
20260 In many cases, holding properly encapsulated resources using RAII "owning" objects can eliminate the need to write these operations yourself. (See Item 13.)
20262 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.
20264 **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.
20265 In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics.
20266 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.)
20268 **References**: [\[C++CS\]](#C++CS) Item 52; [\[Cline99\]](#Cline99) §30.01-14, [\[Koenig97\]](#Koenig97) §4, [\[Stroustrup00\]](#Stroustrup00) §5.5, §10.4, [\[SuttHysl04b\]](#SuttHysl04b)
20270 Resource management rule summary:
20272 * [Provide strong resource safety; that is, never leak anything that you think of as a resource](#Cr-safety)
20273 * [Never throw while holding a resource not owned by a handle](#Cr-never)
20274 * [A "raw" pointer or reference is never a resource handle](#Cr-raw)
20275 * [Never let a pointer outlive the object it points to](#Cr-outlive)
20276 * [Use templates to express containers (and other resource handles)](#Cr-templates)
20277 * [Return containers by value (relying on move or copy elision for efficiency)](#Cr-value-return)
20278 * [If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations](#Cr-handle)
20279 * [If a class is a container, give it an initializer-list constructor](#Cr-list)
20281 ### <a name="Cr-safety"></a>Provide strong resource safety; that is, never leak anything that you think of as a resource
20283 ##### Reason
20285 Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations.
20287 **Alternative formulation**: Have every resource represented as an object of some class managing its lifetime.
20289 ##### Example
20291     template<class T>
20292     class Vector {
20293     // ...
20294     private:
20295         T* elem;   // sz elements on the free store, owned by the class object
20296         int sz;
20297     };
20299 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.).
20301 ##### Example
20303     ??? "odd" non-memory resource ???
20305 ##### Enforcement
20307 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.
20309 ### <a name="Cr-never"></a>Never throw while holding a resource not owned by a handle
20311 ##### Reason
20313 That would be a leak.
20315 ##### Example
20317     void f(int i)
20318     {
20319         FILE* f = fopen("a file", "r");
20320         ifstream is { "another file" };
20321         // ...
20322         if (i == 0) return;
20323         // ...
20324         fclose(f);
20325     }
20327 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:
20329     void f(int i)
20330     {
20331         unique_ptr<FILE, int(*)(FILE*)> f(fopen("a file", "r"), fclose);
20332         // ...
20333         if (i == 0) return;
20334         // ...
20335     }
20337 Better:
20339     void f(int i)
20340     {
20341         ifstream input {"a file"};
20342         // ...
20343         if (i == 0) return;
20344         // ...
20345     }
20347 ##### Enforcement
20349 A checker must consider all "naked pointers" suspicious.
20350 A checker probably must rely on a human-provided list of resources.
20351 For starters, we know about the standard-library containers, `string`, and smart pointers.
20352 The use of `span` and `string_span` should help a lot (they are not resource handles).
20354 ### <a name="Cr-raw"></a>A "raw" pointer or reference is never a resource handle
20356 ##### Reason
20358 To be able to distinguish owners from views.
20360 ##### Note
20362 This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr<T>` and `Range<T>` are not owners.
20364 ### <a name="Cr-outlive"></a>Never let a pointer outlive the object it points to
20366 ##### Reason
20368 To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.
20370 ##### Example
20372     string* bad()   // really bad
20373     {
20374         vector<string> v = { "This", "will", "cause", "trouble", "!" };
20375         // leaking a pointer into a destroyed member of a destroyed object (v)
20376         return &v[0];
20377     }
20379     void use()
20380     {
20381         string* p = bad();
20382         vector<int> xx = {7, 8, 9};
20383         // undefined behavior: x may not be the string "This"
20384         string x = *p;
20385         // undefined behavior: we don't know what (if anything) is allocated a location p
20386         *p = "Evil!";
20387     }
20389 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.
20391 ##### Enforcement
20393 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.
20395 ### <a name="Cr-templates"></a>Use templates to express containers (and other resource handles)
20397 ##### Reason
20399 To provide statically type-safe manipulation of elements.
20401 ##### Example
20403     template<typename T> class Vector {
20404         // ...
20405         T* elem;   // point to sz elements of type T
20406         int sz;
20407     };
20409 ### <a name="Cr-value-return"></a>Return containers by value (relying on move or copy elision for efficiency)
20411 ##### Reason
20413 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).
20415 ##### Example
20417     vector<int> get_large_vector()
20418     {
20419         return ...;
20420     }
20422     auto v = get_large_vector(); //  return by value is ok, most modern compilers will do copy elision
20424 ##### Exception
20426 See the Exceptions in [F.20](#Rf-out).
20428 ##### Enforcement
20430 Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`).
20432 ### <a name="Cr-handle"></a>If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations
20434 ##### Reason
20436 To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource.
20438 ##### Example
20440     ??? Messing with pointers
20442 ##### Note
20444 If all members are resource handles, rely on the default special operations where possible.
20446     template<typename T> struct Named {
20447         string name;
20448         T value;
20449     };
20451 Now `Named` has a default constructor, a destructor, and efficient copy and move operations, provided `T` has.
20453 ##### Enforcement
20455 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.
20457 ### <a name="Cr-list"></a>If a class is a container, give it an initializer-list constructor
20459 ##### Reason
20461 It is common to need an initial set of elements.
20463 ##### Example
20465     template<typename T> class Vector {
20466     public:
20467         Vector(std::initializer_list<T>);
20468         // ...
20469     };
20471     Vector<string> vs { "Nygaard", "Ritchie" };
20473 ##### Enforcement
20475 When is a class a container? ???
20477 # <a name="S-glossary"></a>Glossary
20479 A relatively informal definition of terms used in the guidelines
20480 (based of the glossary in [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html))
20482 More information on many topics about C++ can be found on the [Standard C++ Foundation](https://isocpp.org)'s site. 
20484 * *ABI*: Application Binary Interface, a specification for a specific hardware platform combined with the operating system. Contrast with API.
20485 * *abstract class*: a class that cannot be directly used to create objects; often used to define an interface to derived classes.
20486   A class is made abstract by having a pure virtual function or only protected constructors.
20487 * *abstraction*: a description of something that selectively and deliberately ignores (hides) details (e.g., implementation details); selective ignorance.
20488 * *address*: a value that allows us to find an object in a computer's memory.
20489 * *algorithm*: a procedure or formula for solving a problem; a finite series of computational steps to produce a result.
20490 * *alias*: an alternative way of referring to an object; often a name, pointer, or reference.
20491 * *API*: Application Programming Interface, a set of methods that form the communication between various software components. Contrast with ABI.
20492 * *application*: a program or a collection of programs that is considered an entity by its users.
20493 * *approximation*: something (e.g., a value or a design) that is close to the perfect or ideal (value or design).
20494   Often an approximation is a result of trade-offs among ideals.
20495 * *argument*: a value passed to a function or a template, in which it is accessed through a parameter.
20496 * *array*: a homogeneous sequence of elements, usually numbered, e.g., \[0:max).
20497 * *assertion*: a statement inserted into a program to state (assert) that something must always be true at this point in the program.
20498 * *base class*: a class used as the base of a class hierarchy. Typically a base class has one or more virtual functions.
20499 * *bit*: the basic unit of information in a computer. A bit can have the value 0 or the value 1.
20500 * *bug*: an error in a program.
20501 * *byte*: the basic unit of addressing in most computers. Typically, a byte holds 8 bits.
20502 * *class*: a user-defined type that may contain data members, function members, and member types.
20503 * *code*: a program or a part of a program; ambiguously used for both source code and object code.
20504 * *compiler*: a program that turns source code into object code.
20505 * *complexity*: a hard-to-precisely-define notion or measure of the difficulty of constructing a solution to a problem or of the solution itself.
20506   Sometimes complexity is used to (simply) mean an estimate of the number of operations needed to execute an algorithm.
20507 * *computation*: the execution of some code, usually taking some input and producing some output.
20508 * *concept*: (1) a notion, and idea; (2) a set of requirements, usually for a template argument.
20509 * *concrete class*: class for which objects can be created.
20510 * *constant*: a value that cannot be changed (in a given scope); not mutable.
20511 * *constructor*: an operation that initializes ("constructs") an object.
20512   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).
20513 * *container*: an object that holds elements (other objects).
20514 * *copy*: an operation that makes two object have values that compare equal. See also move.
20515 * *correctness*: a program or a piece of a program is correct if it meets its specification.
20516   Unfortunately, a specification can be incomplete or inconsistent, or can fail to meet users' reasonable expectations.
20517   Thus, to produce acceptable code, we sometimes have to do more than just follow the formal specification.
20518 * *cost*: the expense (e.g., in programmer time, run time, or space) of producing a program or of executing it.
20519   Ideally, cost should be a function of complexity.
20520 * *customization point*: ???
20521 * *data*: values used in a computation.
20522 * *debugging*: the act of searching for and removing errors from a program; usually far less systematic than testing.
20523 * *declaration*: the specification of a name with its type in a program.
20524 * *definition*: a declaration of an entity that supplies all information necessary to complete a program using the entity.
20525   Simplified definition: a declaration that allocates memory.
20526 * *derived class*: a class derived from one or more base classes.
20527 * *design*: an overall description of how a piece of software should operate to meet its specification.
20528 * *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.
20529 * *encapsulation*: protecting something meant to be private (e.g., implementation details) from unauthorized access.
20530 * *error*: a mismatch between reasonable expectations of program behavior (often expressed as a requirement or a users' guide) and what a program actually does.
20531 * *executable*: a program ready to be run (executed) on a computer.
20532 * *feature creep*: a tendency to add excess functionality to a program "just in case."
20533 * *file*: a container of permanent information in a computer.
20534 * *floating-point number*: a computer's approximation of a real number, such as 7.93 and 10.78e-3.
20535 * *function*: a named unit of code that can be invoked (called) from different parts of a program; a logical unit of computation.
20536 * *generic programming*: a style of programming focused on the design and efficient implementation of algorithms.
20537   A generic algorithm will work for all argument types that meet its requirements. In C++, generic programming typically uses templates.
20538 * *global variable*: technically, a named object in namespace scope.
20539 * *handle*: a class that allows access to another through a member pointer or reference. See also resource, copy, move.
20540 * *header*: a file containing declarations used to share interfaces between parts of a program.
20541 * *hiding*: the act of preventing a piece of information from being directly seen or accessed.
20542   For example, a name from a nested (inner) scope can prevent that same name from an outer (enclosing) scope from being directly used.
20543 * *ideal*: the perfect version of something we are striving for. Usually we have to make trade-offs and settle for an approximation.
20544 * *implementation*: (1) the act of writing and testing code; (2) the code that implements a program.
20545 * *infinite loop*: a loop where the termination condition never becomes true. See iteration.
20546 * *infinite recursion*: a recursion that doesn't end until the machine runs out of memory to hold the calls.
20547   In reality, such recursion is never infinite but is terminated by some hardware error.
20548 * *information hiding*: the act of separating interface and implementation, thus hiding implementation details not meant for the user's attention and providing an abstraction.
20549 * *initialize*: giving an object its first (initial) value.
20550 * *input*: values used by a computation (e.g., function arguments and characters typed on a keyboard).
20551 * *integer*: a whole number, such as 42 and -99.
20552 * *interface*: a declaration or a set of declarations specifying how a piece of code (such as a function or a class) can be called.
20553 * *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.
20554 * *iteration*: the act of repeatedly executing a piece of code; see recursion.
20555 * *iterator*: an object that identifies an element of a sequence.
20556 * *ISO*: International Organization for Standardization. The C++ language is an ISO standard, ISO/IEC 14882. More information at [iso.org](http://iso.org).
20557 * *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.
20558 * *lifetime*: the time from the initialization of an object until it becomes unusable (goes out of scope, is deleted, or the program terminates).
20559 * *linker*: a program that combines object code files and libraries into an executable program.
20560 * *literal*: a notation that directly specifies a value, such as 12 specifying the integer value "twelve."
20561 * *loop*: a piece of code executed repeatedly; in C++, typically a for-statement or a while-statement.
20562 * *move*: an operation that transfers a value from one object to another leaving behind a value representing "empty." See also copy.
20563 * *mutable*: changeable; the opposite of immutable, constant, and invariable.
20564 * *object*: (1) an initialized region of memory of a known type which holds a value of that type; (2) a region of memory.
20565 * *object code*: output from a compiler intended as input for a linker (for the linker to produce executable code).
20566 * *object file*: a file containing object code.
20567 * *object-oriented programming*: (OOP) a style of programming focused on the design and use of classes and class hierarchies.
20568 * *operation*: something that can perform some action, such as a function and an operator.
20569 * *output*: values produced by a computation (e.g., a function result or lines of characters written on a screen).
20570 * *overflow*: producing a value that cannot be stored in its intended target.
20571 * *overload*: defining two functions or operators with the same name but different argument (operand) types.
20572 * *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.
20573 * *owner*: an object responsible for releasing a resource.
20574 * *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.
20575 * *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.
20576 * *pointer*: (1) a value used to identify a typed object in memory; (2) a variable holding such a value.
20577 * *post-condition*: a condition that must hold upon exit from a piece of code, such as a function or a loop.
20578 * *pre-condition*: a condition that must hold upon entry into a piece of code, such as a function or a loop.
20579 * *program*: code (possibly with associated data) that is sufficiently complete to be executed by a computer.
20580 * *programming*: the art of expressing solutions to problems as code.
20581 * *programming language*: a language for expressing programs.
20582 * *pseudo code*: a description of a computation written in an informal notation rather than a programming language.
20583 * *pure virtual function*: a virtual function that must be overridden in a derived class.
20584 * *RAII*: ("Resource Acquisition Is Initialization") a basic technique for resource management based on scopes.
20585 * *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.
20586 * *recursion*: the act of a function calling itself; see also iteration.
20587 * *reference*: (1) a value describing the location of a typed value in memory; (2) a variable holding such a value.
20588 * *regular expression*: a notation for patterns in character strings.
20589 * *regular*: a type that behaves similarly to built-in types like `int` and can be compared with `==`.
20590 In particular, an object of a regular type can be copied and the result of a copy is a separate object that compares equal to the original. See also *semiregular type*.
20591 * *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.
20592 * *resource*: something that is acquired and must later be released, such as a file handle, a lock, or memory. See also handle, owner.
20593 * *rounding*: conversion of a value to the mathematically nearest value of a less precise type.
20594 * *RTTI*: Run-Time Type Information. ???
20595 * *scope*: the region of program text (source code) in which a name can be referred to.
20596 * *semiregular*: a type that behaves roughtly like an built-in type like `int`, but possibly without a `==` operator. See also *regular type*.
20597 * *sequence*: elements that can be visited in a linear order.
20598 * *software*: a collection of pieces of code and associated data; often used interchangeably with program.
20599 * *source code*: code as produced by a programmer and (in principle) readable by other programmers.
20600 * *source file*: a file containing source code.
20601 * *specification*: a description of what a piece of code should do.
20602 * *standard*: an officially agreed upon definition of something, such as a programming language.
20603 * *state*: a set of values.
20604 * *STL*: the containers, iterators, and algorithms part of the standard library.
20605 * *string*: a sequence of characters.
20606 * *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.
20607 * *subtype*: derived type; a type that has all the properties of a type and possibly more.
20608 * *supertype*: base type; a type that has a subset of the properties of a type.
20609 * *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.
20610 * *TS*: [Technical Specification](https://www.iso.org/deliverables-all.html?type=ts), A Technical Specification addresses work still under technical development, or where it is believed that there will be a future, but not immediate, possibility of agreement on an International Standard. A Technical Specification is published for immediate use, but it also provides a means to obtain feedback. The aim is that it will eventually be transformed and republished as an International Standard. 
20611 * *template*: a class or a function parameterized by one or more types or (compile-time) values; the basic C++ language construct supporting generic programming.
20612 * *testing*: a systematic search for errors in a program.
20613 * *trade-off*: the result of balancing several design and implementation criteria.
20614 * *truncation*: loss of information in a conversion from a type into another that cannot exactly represent the value to be converted.
20615 * *type*: something that defines a set of possible values and a set of operations for an object.
20616 * *uninitialized*: the (undefined) state of an object before it is initialized.
20617 * *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.
20618 * *use case*: a specific (typically simple) use of a program meant to test its functionality and demonstrate its purpose.
20619 * *value*: a set of bits in memory interpreted according to a type.
20620 * *variable*: a named object of a given type; contains a value unless uninitialized.
20621 * *virtual function*: a member function that can be overridden in a derived class.
20622 * *word*: a basic unit of memory in a computer, often the unit used to hold an integer.
20624 # <a name="S-unclassified"></a>To-do: Unclassified proto-rules
20626 This is our to-do list.
20627 Eventually, the entries will become rules or parts of rules.
20628 Alternatively, we will decide that no change is needed and delete the entry.
20630 * No long-distance friendship
20631 * Should physical design (what's in a file) and large-scale design (libraries, groups of libraries) be addressed?
20632 * Namespaces
20633 * Avoid using directives in the global scope (except for std, and other "fundamental" namespaces (e.g. experimental))
20634 * 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?
20635 * Should there be inline namespaces (à la `std::literals::*_literals`)?
20636 * Avoid implicit conversions
20637 * 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
20638 * Always initialize variables, use initialization lists for member variables.
20639 * 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. :)
20640 * Use `const`-ness wherever possible: member functions, variables and (yippee) `const_iterators`
20641 * Use `auto`
20642 * `(size)` vs. `{initializers}` vs. `{Extent{size}}`
20643 * Don't overabstract
20644 * Never pass a pointer down the call stack
20645 * falling through a function bottom
20646 * 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?
20647 * 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?
20648 * Speaking of lambdas, what would weigh in on the decision between lambdas and (local?) classes in algorithm calls and other callback scenarios?
20649 * 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?
20650 * What to do with leaks out of temporaries? : `p = (s1 + s2).c_str();`
20651 * pointer/iterator invalidation leading to dangling pointers:
20653         void bad()
20654         {
20655             int* p = new int[700];
20656             int* q = &p[7];
20657             delete p;
20659             vector<int> v(700);
20660             int* q2 = &v[7];
20661             v.resize(900);
20663             // ... use q and q2 ...
20664         }
20666 * LSP
20667 * private inheritance vs/and membership
20668 * avoid static class members variables (race conditions, almost-global variables)
20670 * Use RAII lock guards (`lock_guard`, `unique_lock`, `shared_lock`), never call `mutex.lock` and `mutex.unlock` directly (RAII)
20671 * Prefer non-recursive locks (often used to work around bad reasoning, overhead)
20672 * 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`?
20673 * If two or more mutexes must be acquired at the same time, use `std::lock` (or another deadlock avoidance algorithm?)
20674 * 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.
20675 * 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)
20676 * 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)
20677 * 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)
20679 * rules for arithmetic
20681 # Bibliography
20683 * <a name="Alexandrescu01"></a>
20684   \[Alexandrescu01]:  A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
20685 * <a name="Cplusplus03"></a>
20686   \[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).
20687 * <a name="CplusplusCS"></a>
20688   \[C++CS]:           ???
20689 * <a name="Cargill92"></a>
20690   \[Cargill92]:       T. Cargill. C++ Programming Style (Addison-Wesley, 1992).
20691 * <a name="Cline99"></a>
20692   \[Cline99]:         M. Cline, G. Lomow, and M. Girou. C++ FAQs (2ndEdition) (Addison-Wesley, 1999).
20693 * <a name="Dewhurst03"></a>
20694   \[Dewhurst03]:      S. Dewhurst. C++ Gotchas (Addison-Wesley, 2003).
20695 * <a name="Henricson97"></a>
20696   \[Henricson97]:     M. Henricson and E. Nyquist. Industrial Strength C++ (Prentice Hall, 1997).
20697 * <a name="Koenig97"></a>
20698   \[Koenig97]:        A. Koenig and B. Moo. Ruminations on C++ (Addison-Wesley, 1997).
20699 * <a name="Lakos96"></a>
20700   \[Lakos96]:         J. Lakos. Large-Scale C++ Software Design (Addison-Wesley, 1996).
20701 * <a name="Meyers96"></a>
20702   \[Meyers96]:        S. Meyers. More Effective C++ (Addison-Wesley, 1996).
20703 * <a name="Meyers97"></a>
20704   \[Meyers97]:        S. Meyers. Effective C++ (2nd Edition) (Addison-Wesley, 1997).
20705 * <a name="Meyers15"></a>
20706   \[Meyers15]:        S. Meyers. Effective Modern C++ (O'Reilly, 2015).
20707 * <a name="Murray93"></a>
20708   \[Murray93]:        R. Murray. C++ Strategies and Tactics (Addison-Wesley, 1993).
20709 * <a name="Stroustrup94"></a>
20710   \[Stroustrup94]:    B. Stroustrup. The Design and Evolution of C++ (Addison-Wesley, 1994).
20711 * <a name="Stroustrup00"></a>
20712   \[Stroustrup00]:    B. Stroustrup. The C++ Programming Language (Special 3rdEdition) (Addison-Wesley, 2000).
20713 * <a name="Stroustrup05"></a>
20714   \[Stroustrup05]:    B. Stroustrup. [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
20715 * <a name="Stroustrup13"></a>
20716   \[Stroustrup13]:    B. Stroustrup. [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html). Addison Wesley 2013.
20717 * <a name="Stroustrup14"></a>
20718   \[Stroustrup14]:    B. Stroustrup. [A Tour of C++](http://www.stroustrup.com/Tour.html).
20719   Addison Wesley 2014.
20720 * <a name="SuttHysl04b"></a>
20721   \[SuttHysl04b]:     H. Sutter and J. Hyslop. "Collecting Shared Objects" (C/C++ Users Journal, 22(8), August 2004).
20722 * <a name="SuttAlex05"></a>
20723   \[SuttAlex05]:      H. Sutter and  A. Alexandrescu. C++ Coding Standards. Addison-Wesley 2005.
20724 * <a name="Sutter00"></a>
20725   \[Sutter00]:        H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
20726 * <a name="Sutter02"></a>
20727   \[Sutter02]:        H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
20728 * <a name="Sutter04"></a>
20729   \[Sutter04]:        H. Sutter. Exceptional C++ Style (Addison-Wesley, 2004).
20730 * <a name="Taligent94"></a>
20731   \[Taligent94]: Taligent's Guide to Designing Programs (Addison-Wesley, 1994).