1 # <a name="main"></a> C++ Core Guidelines
7 * [Bjarne Stroustrup](http://www.stroustrup.com)
8 * [Herb Sutter](http://herbsutter.com/)
10 This document is a very early draft. It is inkorrekt, incompleat, and pµøoorly formatted.
11 Had it been an open source (code) project, this would have been release 0.6.
12 Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
13 Contributing to this project requires agreeing to a Contributor License. See the accompanying LICENSE file for details.
14 We make this project available to "friendly users" to use, copy, modify, and derive from, hoping for constructive input.
16 Comments and suggestions for improvements are most welcome.
17 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
18 When commenting, please note [the introduction](#S-introduction) that outlines our aims and general approach.
19 The list of contributors is [here](#SS-ack).
23 * The sets of rules have not been thoroughly checked for completeness, consistency, or enforceability.
24 * Triple question marks (???) mark known missing information
25 * Update reference sections; many pre-C++11 sources are too old.
26 * For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified)
28 You can [Read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
30 * [P: Philosophy](#S-philosophy)
31 * [I: Interfaces](#S-interfaces)
32 * [F: Functions](#S-functions)
33 * [C: Classes and class hierarchies](#S-class)
34 * [Enum: Enumerations](#S-enum)
35 * [ES: Expressions and statements](#S-expr)
36 * [E: Error handling](#S-errors)
37 * [R: Resource management](#S-resource)
38 * [T: Templates and generic programming](#S-templates)
39 * [CP: Concurrency](#S-concurrency)
40 * [SL: The Standard library](#S-stdlib)
41 * [SF: Source files](#S-source)
42 * [CPL: C-style programming](#S-cpl)
43 * [PRO: Profiles](#S-profile)
44 * [GSL: Guideline support library](#S-gsl)
45 * [FAQ: Answers to frequently asked questions](#S-faq)
49 * [NL: Naming and layout](#S-naming)
50 * [PER: Performance](#S-performance)
51 * [N: Non-Rules and myths](#S-not)
52 * [RF: References](#S-references)
53 * [Appendix A: Libraries](#S-libraries)
54 * [Appendix B: Modernizing code](#S-modernizing)
55 * [Appendix C: Discussion](#S-discussion)
56 * [To-do: Unclassified proto-rules](#S-unclassified)
58 or look at a specific language feature
60 * [assignment](#S-???)
62 * [constructor](#SS-ctor)
63 * [derived `class`](#SS-hier)
64 * [destructor](#SS-ctor)
65 * [exception](#S-errors)
67 * [`inline`](#S-class)
68 * [initialization](#S-???)
69 * [lambda expression](#SS-lambdas)
71 * [`public`, `private`, and `protected`](#S-???)
72 * [`static_assert`](#S-???)
73 * [`struct`](#S-class)
74 * [`template`](#S-???)
75 * [`unsigned`](#S-???)
76 * [`virtual`](#SS-hier)
78 Definitions of terms used to express and discuss the rules, that are not language-technical, but refer to design and programming techniques
90 # <a name="S-abstract"></a> Abstract
92 This document is a set of guidelines for using C++ well.
93 The aim of this document is to help people to use modern C++ effectively.
94 By "modern C++" we mean C++11 and C++14 (and soon C++17).
95 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?
97 The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management, and concurrency.
98 Such rules affect application architecture and library design.
99 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.
100 And it will run fast - you can afford to do things right.
102 We are less concerned with low-level issues, such as naming conventions and indentation style.
103 However, no topic that can help a programmer is out of bounds.
105 Our initial set of rules emphasizes safety (of various forms) and simplicity.
106 They may very well be too strict.
107 We expect to have to introduce more exceptions to better accommodate real-world needs.
108 We also need more rules.
110 You will find some of the rules contrary to your expectations or even contrary to your experience.
111 If we haven't suggested you change your coding style in any way, we have failed!
112 Please try to verify or disprove rules!
113 In particular, we'd really like to have some of our rules backed up with measurements or better examples.
115 You will find some of the rules obvious or even trivial.
116 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.
118 The rules are designed to be supported by an analysis tool.
119 Violations of rules will be flagged with references (or links) to the relevant rule.
120 We do not expect you to memorize all the rules before trying to write code.
122 The rules are meant for gradual introduction into a code base.
123 We plan to build tools for that and hope others will too.
125 Comments and suggestions for improvements are most welcome.
126 We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve.
128 # <a name="S-introduction"></a> In: Introduction
130 This is a set of core guidelines for modern C++, C++14, and taking likely future enhancements and taking ISO Technical Specifications (TSs) into account.
131 The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
133 Introduction summary:
135 * [In.target: Target readership](#SS-readers)
136 * [In.aims: Aims](#SS-aims)
137 * [In.not: Non-aims](#SS-non)
138 * [In.force: Enforcement](#SS-force)
139 * [In.struct: The structure of this document](#SS-struct)
140 * [In.sec: Major sections](#SS-sec)
142 ## <a name="SS-readers"></a> In.target: Target readership
144 All C++ programmers. This includes [programmers who might consider C](#S-cpl).
146 ## <a name="SS-aims"></a> In.aims: Aims
148 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.
150 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.
151 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").
152 Consider these rules ideals for new code, opportunities to exploit when working on older code, and try to approximate these ideas as closely as feasible.
155 ### <a name="R0"></a> In.0: Don't panic!
157 Take the time to understand the implications of a guideline rule on your program.
159 These guidelines are designed according to the "subset of a superset" principle ([Stroustrup05](#Stroustrup05)).
160 They do not simply define a subset of C++ to be used (for reliability, safety, performance, or whatever).
161 Instead, they strongly recommend the use of a few simple "extensions" ([library components](#S-gsl))
162 that make the use of the most error-prone features of C++ redundant, so that they can be banned (in our set of rules).
164 The rules emphasize static type safety and resource safety.
165 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).
166 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.
168 Many of the rules are prescriptive.
169 We are uncomfortable with rules that simply states "don't do that!" without offering an alternative.
170 One consequence of that is that some rules can be supported only by heuristics, rather than precise and mechanically verifiable checks.
171 Other rules articulate general principles. For these more general rules, more detailed and specific rules provide partial checking.
173 These guidelines address a core of C++ and its use.
174 We expect that most large organizations, specific application areas, and even large projects will need further rules, possibly further restrictions, and further library support.
175 For example, hard-real time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
176 We encourage the development of such more specific rules as addenda to these core guidelines.
177 Build your ideal small foundation library and use that, rather than lowering you level of programming to glorified assembly code.
179 The rules are designed to allow [gradual adoption](#S-modernizing).
181 Some rules aim to increase various forms of safety while others aim to reduce the likelihood of accidents, many do both.
182 The guidelines aimed at preventing accidents often ban perfectly legal C++.
183 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.
185 ## <a name="SS-non"></a> In.not: Non-aims
187 The rules are not intended to be minimal or orthogonal.
188 In particular, general rules can be simple, but unenforceable.
189 Also, it is often hard to understand the implications of a general rule.
190 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.
191 We provide rules aimed as helping novices as well as rules supporting expert use.
192 Some rules can be completely enforced, but others are based on heuristics.
194 These rules are not meant to be read serially, like a book.
195 You can browse through them using the links.
196 However, their main intended use is to be targets for tools.
197 That is, a tool looks for violations and the tool returns links to violated rules.
198 The rules then provide reasons, examples of potential consequences of the violation, and suggested remedies.
200 These guidelines are not intended to be a substitute for a tutorial treatment of C++.
201 If you need a tutorial for some given level of experience, see [the references](#S-references).
203 This is not a guide on how to convert old C++ code to more modern code.
204 It is meant to articulate ideas for new code in a concrete fashion.
205 However, see [the modernization section](#S-modernizing) for some possible approaches to modernizing/rejuvenating/upgrading.
206 Importantly, the rules support gradual adoption: It is typically infeasible to convert all of a large code base at once.
208 These guidelines are not meant to be complete or exact in every language-technical detail.
209 For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
211 The rules are not intended to force you to write in an impoverished subset of C++.
212 They are *emphatically* not meant to define a, say, Java-like subset of C++.
213 They are not meant to define a single "one true C++" language.
214 We value expressiveness and uncompromised performance.
216 The rules are not value-neutral.
217 They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance.
218 They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance.
220 ## <a name="SS-force"></a> In.force: Enforcement
222 Rules with no enforcement are unmanageable for large code bases.
223 Enforcement of all rules is possible only for a small weak set of rules or for a specific user community.
224 But we want lots of rules, and we want rules that everybody can use.
225 But different people have different needs.
226 But people don't like to read lots of rules.
227 But people can't remember many rules.
228 So, we need subsetting to meet a variety of needs.
229 But arbitrary subsetting leads to chaos: We want guidelines that help a lot of people, make code more uniform, and strongly encourages people to modernize their code.
230 We want to encourage best practices, rather than leave all to individual choices and management pressures.
231 The ideal is to use all rules; that gives the greatest benefits.
233 This adds up to quite a few dilemmas.
234 We try to resolve those using tools.
235 Each rule has an **Enforcement** section listing ideas for enforcement.
236 Enforcement might be by code review, by static analysis, by compiler, or by run-time checks.
237 Wherever possible, we prefer "mechanical" checking (humans are slow and bore easily) and static checking.
238 Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed fat" - if that's what you want, you know where to find it.
239 Where appropriate, we label a rule (in the **Enforcement** sections) with the name of groups of related rules (called "profiles").
240 A rule can be part of several profiles, or none.
241 For a start, we have a few profiles corresponding to common needs (desires, ideals):
243 * **types**: No type violations (reinterpreting a `T` as a `U` through casts/unions/varargs)
244 * **bounds**: No bounds violations (accessing beyond the range of an array)
245 * **lifetime**: No leaks (failing to `delete` or multiple `delete`) and no access to invalid objects (dereferencing `nullptr`, using a dangling reference).
247 The profiles are intended to be used by tools, but also serve as an aid to the human reader.
248 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.
250 ## <a name="SS-struct"></a> In.struct: The structure of this document
252 Each rule (guideline, suggestion) can have several parts:
254 * The rule itself - e.g., **no naked `new`**
255 * A rule reference number - e.g., **C.7** (the 7th rule related to classes).
256 Since the major sections are not inherently ordered, we use a letter as the first part of a rule reference "number".
257 We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
258 * **Reason**s (rationales) - because programmers find it hard to follow rules they don't understand
259 * **Example**s - because rules are hard to understand in the abstract; can be positive or negative
260 * **Alternative**s - for "don't do this" rules
261 * **Exception**s - we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
262 * **Enforcement** - ideas about how the rule might be checked "mechanically"
263 * **See also**s - references to related rules and/or further discussion (in this document or elsewhere)
264 * **Note**s (comments) - something that needs saying that doesn't fit the other classifications
265 * **Discussion** - references to more extensive rationale and/or examples placed outside the main lists of rules
267 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.
268 We hope that "mechanical" tools will improve with time to approximate what such an expert programmer notices.
269 Also, we assume that the rules will be refined over time to make them more precise and checkable.
271 A rule is aimed at being simple, rather than carefully phrased to mention every alternative and special case.
272 Such information is found in the **Alternative** paragraphs and the [Discussion](#S-discussion) sections.
273 If you don't understand a rule or disagree with it, please visit its **Discussion**.
274 If you feel that a discussion is missing or incomplete, send us an email.
276 This is not a language manual.
277 It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
278 Recommended information sources can be found in [the references](#S-references).
280 ## <a name="SS-sec"></a> In.sec: Major sections
282 * [P: Philosophy](#S-philosophy)
283 * [I: Interfaces](#S-interfaces)
284 * [F: Functions](#S-functions)
285 * [C: Classes and class hierarchies](#S-class)
286 * [Enum: Enumerations](#S-enum)
287 * [ES: Expressions and statements](#S-expr)
288 * [E: Error handling](#S-errors)
289 * [R: Resource management](#S-resource)
290 * [T: Templates and generic programming](#S-templates)
291 * [CP: Concurrency](#S-concurrency)
292 * [SL: The Standard library](#S-stdlib)
293 * [SF: Source files](#S-source)
294 * [CPL: C-style programming](#S-cpl)
295 * [PRO: Profiles](#S-profile)
296 * [GSL: Guideline support library](#S-gsl)
297 * [FAQ: Answers to frequently asked questions](#S-faq)
301 * [NL: Naming and layout](#S-naming)
302 * [PER: Performance](#S-performance)
303 * [N: Non-Rules and myths](#S-not)
304 * [RF: References](#S-references)
305 * [Appendix A: Libraries](#S-libraries)
306 * [Appendix B: Modernizing code](#S-modernizing)
307 * [Appendix C: Discussion](#S-discussion)
308 * [To-do: Unclassified proto-rules](#S-unclassified)
310 These sections are not orthogonal.
312 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.
313 The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").
315 # <a name="S-philosophy"></a> P: Philosophy
317 The rules in this section are very general.
319 Philosophy rules summary:
321 * [P.1: Express ideas directly in code](#Rp-direct)
322 * [P.2: Write in ISO Standard C++](#Rp-C++)
323 * [P.3: Express intent](#Rp-what)
324 * [P.4: Ideally, a program should be statically type safe](#Rp-typesafe)
325 * [P.5: Prefer compile-time checking to run-time checking](#Rp-compile-time)
326 * [P.6: What cannot be checked at compile time should be checkable at run time](#Rp-run-time)
327 * [P.7: Catch run-time errors early](#Rp-early)
328 * [P.8: Don't leak any resource](#Rp-leak)
329 * [P.9: Don't waste time or space](#Rp-waste)
331 Philosophical rules are generally not mechanically checkable.
332 However, individual rules reflecting these philosophical themes are.
333 Without a philosophical basis the more concrete/specific/checkable rules lack rationale.
335 ### <a name="Rp-direct"></a> P.1: Express ideas directly in code
339 Compilers don't read comments (or design documents) and neither do many programmers (consistently).
340 What is expressed in code has a defined semantics and can (in principle) be checked by compilers and other tools.
347 Month month() const; // do
348 int month(); // don't
352 The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object.
353 The second version leaves the reader guessing and opens more possibilities for uncaught bugs.
357 void do_something(vector<string>& v)
362 int index = 0; // bad
363 for (int i = 0; i < v.size(); ++i)
371 That loop is a restricted form of `std::find`.
372 A much clearer expression of intent would be:
374 void do_something(vector<string>& v)
379 auto p = find(v, val); // better
383 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.
385 A C++ programmer should know the basics of the standard library, and use it where appropriate.
386 Any programmer should know the basics of the foundation libraries of the project being worked on, and use it appropriately.
387 Any programmer using these guidelines should know the [Guidelines Support Library](#S-gsl), and use it appropriately.
391 change_speed(double s); // bad: what does s signify?
395 A better approach is to be explicit about the meaning of the double (new speed or delta on old speed?) and the unit used:
397 change_speed(Speed s); // better: the meaning of s is specified
399 change_speed(2.3); // error: no unit
400 change_speed(23m / 10s); // meters per second
402 We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone.
403 If we wanted both absolute speed and deltas, we would have defined a `Delta` type.
407 Very hard in general.
409 * use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
410 * flag uses of casts (casts neuter the type system)
411 * detect code that mimics the standard library (hard)
413 ### <a name="Rp-C++"></a> P.2: Write in ISO Standard C++
417 This is a set of guidelines for writing ISO Standard C++.
421 There are environments where extensions are necessary, e.g., to access system resources.
422 In such cases, localize the use of necessary extensions and control their use with non-core Coding Guidelines.
426 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.
427 In such cases, control their (dis)use with non-core Coding Guidelines.
431 Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions.
433 ### <a name="Rp-what"></a> P.3: Express intent
437 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.
442 while (i < v.size()) {
443 // ... do something with v[i] ...
446 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.
450 for (auto x : v) { /* do something with x */ }
452 Now, there is no explicit mention of the iteration mechanism, and the loop operates on a copy of elements so that accidental modification cannot happen. If modification is desired, say so:
454 for (auto& x : v) { /* do something with x */ }
456 Sometimes better still, use a named algorithm:
458 for_each(v, [](int x) { /* do something with x */ });
459 for_each(parallel.v, [](int x) { /* do something with x */ });
461 The last variant makes it clear that we are not interested in the order in which the elements of `v` are handled.
463 A programmer should be familiar with
465 * [The guideline support library](#S-gsl)
466 * [The ISO C++ standard library](#S-stdlib)
467 * Whatever foundation libraries are used for the current project(s)
471 Alternative formulation: Say what should be done, rather than just how it should be done.
475 Some language constructs express intent better than others.
479 If two `int`s are meant to be the coordinates of a 2D point, say so:
481 drawline(int, int, int, int); // obscure
482 drawline(Point, Point); // clearer
486 Look for common patterns for which there are better alternatives
488 * simple `for` loops vs. range-`for` loops
489 * `f(T*, int)` interfaces vs. `f(array_view<T>)` interfaces
490 * loop variable in a too large scope
491 * naked `new` and `delete`
492 * functions with many arguments of built-in types
494 There is a huge scope for cleverness and semi-automated program transformation.
496 ### <a name="Rp-typesafe"></a> P.4: Ideally, a program should be statically type safe
500 Ideally, a program would be completely statically (compile-time) type safe.
501 Unfortunately, that is not possible. Problem areas:
507 * narrowing conversions
511 These areas are sources of serious problems (e.g., crashes and security violations).
512 We try to provide alternative techniques.
516 We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
517 Always suggest an alternative.
520 * unions - use `variant`
521 * casts - minimize their use; templates can help
522 * array decay - use `array_view`
523 * range errors - use `array_view`
524 * narrowing conversions - minimize their use and use `narrow` or `narrow_cast` where they are necessary
526 ### <a name="Rp-compile-time"></a> P.5: Prefer compile-time checking to run-time checking
530 Code clarity and performance. You don't need to write error handlers for errors caught at compile time.
534 void initializer(Int x)
535 // Int is an alias used for integers
537 static_assert(sizeof(Int) >= 4); // do: compile-time check
539 int bits = 0; // don't: avoidable code
540 for (Int i = 1; i; i <<= 1)
543 cerr << "Int too small\n";
550 void read(int* p, int n); // read max n integers into *p
554 void read(array_view<int> r); // read into the range of integers r
556 **Alternative formulation**: Don't postpone to run time what can be done well at compile time.
560 * look for pointer arguments
561 * look for run-time checks for range violations.
563 ### <a name="Rp-run-time"></a> P.6: What cannot be checked at compile time should be checkable at run time
567 Leaving hard-to-detect errors in a program is asking for crashes and bad results.
571 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).
575 extern void f(int* p); // separately compiled, possibly dynamically loaded
579 f(new int[n]); // bad: the number of elements is not passed to f()
582 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.
586 We can of course pass the number of elements along with the pointer:
588 extern void f2(int* p, int n); // separately compiled, possibly dynamically loaded
592 f2(new int[n], m); // bad: the wrong number of elements can be passed to f()
595 Passing the number of elements as an argument is better (and far more common) that 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.
597 Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
601 The standard library resource management pointers fail to pass the size when they point to an object:
603 extern void f3(unique_ptr<int[]>, int n); // separately compiled, possibly dynamically loaded
607 f3(make_unique<int[]>(n), m); // bad: pass ownership and size separately
612 We need to pass the pointer and the number of elements as an integral object:
614 extern void f4(vector<int>&); // separately compiled, possibly dynamically loaded
615 extern void f4(array_view<int>); // separately compiled, possibly dynamically loaded
620 f4(v); // pass a reference, retain ownership
621 f4(array_view<int>{v}); // pass a view, retain ownership
624 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.
628 How do we transfer both ownership and all information needed for validating use?
630 vector<int> f5(int n) // OK: move
633 // ... initialize v ...
637 unique_ptr<int[]> f6(int n) // bad: loses n
639 auto p = make_unique<int[]>(n);
640 // ... initialize *p ...
644 owner<int*> f7(int n) // bad: loses n and we might forget to delete
646 owner<int*> p = new int[n];
647 // ... initialize *p ...
654 * show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
655 Or strings as "free-style" options
659 * Flag (pointer, count) interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
662 ### <a name="Rp-early"></a> P.7: Catch run-time errors early
666 Avoid "mysterious" crashes.
667 Avoid errors leading to (possibly unrecognized) wrong results.
671 void increment1(int* p, int n) // bad: error prone
673 for (int i = 0; i < n; ++i) ++p[i];
681 increment1(a, m); // maybe typo, maybe m<=n is supposed
682 // but assume that m == 20
686 Here we made a small error in `use1` that will lead to corrupted data or a crash.
687 The (pointer, count) interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
688 Assuming that we could check subscripts for out of range access, the error would not be discovered until `p[10]` was accessed.
689 We could check earlier and improve the code:
691 void increment2(array_view<int> p)
693 for (int& x : p) ++x;
701 increment2({a, m}); // maybe typo, maybe m<=n is supposed
705 Now, `m<=n` can be checked at the point of call (early) rather than later.
706 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):
713 increment2(a); // the number of elements of a need not be repeated
719 Don't repeatedly check the same value. Don't pass structured data as strings:
721 Date read_date(istream& is); // read date from istream
723 Date extract_date(const string& s); // extract date from string
725 void user1(const string& date) // manipulate date
727 auto d = extract_date(date);
733 Date d = read_date(cin);
735 user1(d.to_string());
739 The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data).
743 Excess checking can be costly.
744 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.
746 class Jet { // Physics says: e*e < x*x + y*y + z*z
748 float fx, fy, fz, fe;
750 Jet(float x, float y, float z, float e)
751 :fx(x), fy(y), fz(z), fe(e)
753 // Should I check here that the values are physically meaningful?
758 // Should I handle the degenerate case here?
759 return sqrt(x*x + y*y + z*z - e*e);
765 The physical law for a jet (`e*e < x*x + y*y + z*z`) is not an invariant because the possibility of measurement errors.
771 * Look at pointers and arrays: Do range-checking early
772 * Look at conversions: eliminate or mark narrowing conversions.
773 * Look for unchecked values coming from input
774 * Look for structured data (objects of classes with invariants) being converted into strings
777 ### <a name="Rp-leak"></a> P.8: Don't leak any resource
781 Essential for long-running programs. Efficiency. Ability to recover from errors.
787 FILE* input = fopen(name, "r");
789 if (something) return; // bad: if something == true, a file handle is leaked
794 Prefer [RAII](#Rr-raii):
798 ifstream input {name};
800 if (something) return; // OK: no leak
804 **See also**: [The resource management section](#S-resource)
808 * Look at pointers: classify them into non-owners (the default) and owners.
809 Where feasible, replace owners with standard-library resource handles (as in the example above).
810 Alternatively, mark an owner as such using `owner` from [the GSL](#S-gsl).
811 * Look for naked `new` and `delete`
812 * Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
814 ### <a name="Rp-waste"></a> P.9: Don't waste time or space
822 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.
826 ??? more and better suggestions for gratuitous waste welcome ???
834 X& operator=(const X& a);
838 X waste(const char* p)
840 if (p == nullptr) throw Nullptr_error{};
842 auto buf = new char[n];
843 if (buf == nullptr) throw Allocation_error{};
844 for (int i = 0; i < n; ++i) buf[i] = p[i];
845 // ... manipulate buffer ...
848 x.s = string(n); // give x.s space for *ps
849 for (int i = 0; i < x.s.size(); ++i) x.s[i] = buf[i]; // copy buf into x.s
856 X x = waste("Typical argument");
860 Yes, this is a caricature, but we have seen every individual mistake in production code, and worse.
861 Note that the layout of `X` guarantees that at least 6 bytes (and most likely more) bytes are wasted.
862 The spurious definition of copy operations disables move semantics so that the return operation is slow.
863 The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`.
864 There are several more performance bugs and gratuitous complication.
868 An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert.
869 However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like.
870 The aim of this rule (and the more specific rules that supports it) is to eliminate most waste related to the use of C++ before it happens.
871 After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines.
875 Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
877 # <a name="S-interfaces"></a> I: Interfaces
879 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.
880 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.
882 Interface rule summary:
884 * [I.1: Make interfaces explicit](#Ri-explicit)
885 * [I.2: Avoid global variables](#Ri-global)
886 * [I.3: Avoid singletons](#Ri-singleton)
887 * [I.4: Make interfaces precisely and strongly typed](#Ri-typed)
888 * [I.5: State preconditions (if any)](#Ri-pre)
889 * [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
890 * [I.7: State postconditions](#Ri-post)
891 * [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
892 * [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
893 * [I.10: Use exceptions to signal a failure to perform a required tasks](#Ri-except)
894 * [I.11: Never transfer ownership by a raw pointer (`T*`)](#Ri-raw)
895 * [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
896 * [I.13: Do not pass an array as a single pointer](#Ri-array)
897 * [I.23: Keep the number of function arguments low](#Ri-nargs)
898 * [I.24: Avoid adjacent unrelated parameters of the same type](#Ri-unrelated)
899 * [I.25: Prefer abstract classes as interfaces to class hierarchies](#Ri-abstract)
900 * [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
904 * [F: Functions](#S-functions)
905 * [C.concrete: Concrete types](#SS-concrete)
906 * [C.hier: Class hierarchies](#SS-hier)
907 * [C.over: Overloading and overloaded operators](#SS-overload)
908 * [C.con: Containers and other resource handles](#SS-containers)
909 * [E: Error handling](#S-errors)
910 * [T: Templates and generic programming](#S-templates)
912 ### <a name="Ri-explicit"></a> I.1: Make interfaces explicit
916 Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
920 Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
924 return (rnd_up) ? ceil(d) : d; // don't: "invisible" dependency
927 It will not be obvious to a caller that the meaning of two calls of `rnd(7.2)` might give different results.
929 **Exception**: Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
930 The use of a non-local control is potentially confusing, but controls only implementation details of an otherwise fixed semantics.
934 Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
936 fprintf(connection, "logging: %d %d %d\n", x, y, s); // don't: no test of printf's return value
938 What if the connection goes down so than no logging output is produced? See Rule I.??.
940 **Alternative**: Throw an exception. An exception cannot be ignored.
942 **Alternative formulation**: Avoid passing information across an interface through non-local state.
943 Note that non-`const` member functions pass information to other member functions through their object's state.
945 **Alternative formulation**: An interface should be a function or a set of functions.
946 Functions can be template functions and sets of functions can be classes or class templates.
950 * (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.
951 * (Simple) A function should not write to variables declared at namespace scope.
953 ### <a name="Ri-global"></a> I.2 Avoid global variables
957 Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
962 // ... lots of stuff ...
963 } data; // non-const data
965 void compute() // don't
970 void output() // don't
975 Who else might modify `data`?
979 Global constants are useful.
983 The rule against global variables applies to namespace scope variables as well.
985 **Alternative**: If you use global (more generally namespace scope data) to avoid copying, consider passing the data as an object by const reference.
986 Another solution is to define the data as the state of some objects and the operations as member functions.
988 **Warning**: Beware of data races: if one thread can access nonlocal data (or data passed by reference) while another thread execute the callee, we can have a data race.
989 Every pointer or reference to mutable data is a potential data race.
993 You cannot have a race condition on immutable data.
995 **Reference**: See the [rules for calling functions](#SS-call).
999 (Simple) Report all non-`const` variables declared at namespace scope.
1001 ### <a name="Ri-singleton"></a> I.3: Avoid singletons
1005 Singletons are basically complicated global objects in disguise.
1010 // ... lots of stuff to ensure that only one Singleton object is created,
1011 // that it is initialized properly, etc.
1014 There are many variants of the singleton idea.
1015 That's part of the problem.
1019 If you don't want a global object to change, declare it `const` or `constexpr`.
1023 You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
1031 This is one of the most effective solutions to problems related to initialization order.
1032 In a multi-threaded environment the initialization of the static object does not introduce a race condition
1033 (unless you carelessly access a shared object from within its constructor).
1035 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.
1039 Very hard in general
1041 * Look for classes with name that includes `singleton`
1042 * Look for classes for which only a single object is created (by counting objects or by examining constructors)
1044 ### <a name="Ri-typed"></a> I.4: Make interfaces precisely and strongly typed
1046 Reason: Types are the simplest and best documentation, have well-defined meaning, and are guaranteed to be checked at compile time.
1047 Also, precisely typed code is often optimized better.
1049 ##### Example, don't
1053 void pass(void* data); // void* is suspicious
1055 Now the callee has to cast the data pointer (back) to a correct type to use it. That is error-prone and often verbose.
1056 Avoid `void*` in interfaces.
1057 Consider using a variant or a pointer to base instead. (Future note: Consider a pointer to concept.)
1059 **Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or something like that.
1065 void draw_rect(int, int, int, int); // great opportunities for mistakes
1067 draw_rect(p.x, p.y, 10, 20); // what does 10, 20 mean?
1069 An `int` can carry arbitrary forms of information, so we must guess about the meaning of the four `int`s.
1070 Most likely, the first two are an `x`,`y` coordinate pair, but what are the last two?
1071 Comments and parameter names can help, but we could be explicit:
1073 void draw_rectangle(Point top_left, Point bottom_right);
1074 void draw_rectangle(Point top_left, Size height_width);
1076 draw_rectangle(p, Point{10, 20}); // two corners
1077 draw_rectangle(p, Size{10, 20}); // one corner and a (height, width) pair
1079 Obviously, we cannot catch all errors through the static type system
1080 (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
1084 In the following example, it is not clear from the interface what time_to_blink means: Seconds? Milliseconds?
1086 void blink_led(int time_to_blink) // bad - the unit is ambiguous
1089 // do something with time_to_blink
1100 std::chrono::duration types introduced in C++11 helps making the unit of time duration explicit.
1102 void blink_led(milliseconds time_to_blink) // good - the unit is explicit
1105 // do something with time_to_blink
1114 The function can also be written in such a way that it will accept any time duration unit.
1116 template<class rep, class period>
1117 void blink_led(duration<rep, period> time_to_blink) // good - accepts any unit
1119 // assuming that millisecond is the smallest relevant unit
1120 auto milliseconds_to_blink = duration_cast<milliseconds>(time_to_blink);
1122 // do something with milliseconds_to_blink
1134 * (Simple) Report the use of `void*` as a parameter or return type.
1135 * (Hard to do well) Look for member functions with many built-in type arguments.
1137 ### <a name="Ri-pre"></a> I.5: State preconditions (if any)
1141 Arguments have meaning that may constrain their proper use in the callee.
1147 double sqrt(double x);
1149 Here `x` must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
1151 double sqrt(double x); // x must be nonnegative
1153 Some preconditions can be expressed as assertions. For example:
1155 double sqrt(double x) { Expects(x >= 0); /* ... */ }
1157 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).
1159 **Reference**: `Expects()` is described in [GSL](#S-gsl).
1163 Prefer a formal specification of requirements, such as `Expects(p != nullptr);` If that is infeasible, use English text in comments, such as
1164 `// the sequence [p:q) is ordered using <`
1168 Most member functions have as a precondition that some class invariant holds.
1169 That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
1170 We don't need to mention it for each member function.
1176 **See also**: The rules for passing pointers.
1178 ### <a name="Ri-expects"></a> I.6: Prefer `Expects()` for expressing preconditions
1182 To make it clear that the condition is a precondition and to enable tool use.
1186 int area(int height, int width)
1188 Expects(height > 0 && width > 0); // good
1189 if (height <= 0 || width <= 0) my_error(); // obscure
1195 Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`. 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?).
1199 Preconditions should be part of the interface rather than part of the implementation, but we don't yet have the language facilities to do that.
1203 `Expects()` can also be used to check a condition in the middle of an algorithm.
1207 (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.
1209 ### <a name="Ri-post"></a> I.7: State postconditions
1213 To detect misunderstandings about the result and possibly catch erroneous implementations.
1219 int area(int height, int width) { return height * width; } // bad
1221 Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
1222 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.
1223 Overflow can happen.
1226 int area(int height, int width)
1228 auto res = height * width;
1235 Consider a famous security bug:
1237 void f() // problematic
1241 memset(buffer, 0, MAX);
1244 There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant `memset()` call:
1250 memset(buffer, 0, MAX);
1251 Ensures(buffer[0] == 0);
1256 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.
1260 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.
1264 Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
1268 void manipulate(Record& r) // don't
1271 // ... no m.unlock() ...
1274 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. Stating the postcondition would have made it clear:
1276 void manipulate(Record& r) // better: hold the mutex m while and only while manipulating r
1279 // ... no m.unlock() ...
1282 The bug is now obvious.
1284 Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
1286 void manipulate(Record& r) // best
1288 lock_guard<mutex> _ {m};
1294 Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
1295 Only postconditions related to the users can be stated in the interface.
1296 Postconditions related only to internal state belongs in the definition/implementation.
1300 (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1302 ### <a name="Ri-ensures"></a> I.8: Prefer `Ensures()` for expressing postconditions
1306 To make it clear that the condition is a postcondition and to enable tool use.
1314 memset(buffer, 0, MAX);
1315 Ensures(buffer[0] == 0);
1320 Postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`. This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.
1322 **Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
1324 Ideally, that `Ensures` should be part of the interface, but that's not easily done. For now, we place it in the definition (function body).
1328 (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.
1330 ### <a name="Ri-concepts"></a> I.9: If an interface is a template, document its parameters using concepts
1334 Make the interface precisely specified and compile-time checkable in the (not so distant) future.
1338 Use the ISO Concepts TS style of requirements specification. For example:
1340 template<typename Iter, typename Val>
1341 // requires InputIterator<Iter> && EqualityComparable<ValueType<Iter>>, Val>
1342 Iter find(Iter first, Iter last, Val v)
1349 Soon (maybe in 2016), most compilers will be able to check `requires` clauses once the `//` is removed.
1351 **See also**: See [generic programming](???) and [???](???)
1355 (Not enforceable yet) 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).
1357 ### <a name="Ri-except"></a> I.10: Use exceptions to signal a failure to perform a required task
1361 It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
1362 This is a major source of errors.
1366 int printf(const char* ...); // bad: return negative number if output fails
1368 template <class F, class ...Args>
1369 explicit thread(F&& f, Args&&... args); // good: throw system_error if unable to start the new thread
1371 ##### Note: What is an error?
1373 An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
1374 Calling code that ignores the error could lead to wrong results or undefined systems state.
1375 For example, not being able to connect to a remote server is not by itself an error:
1376 the server can refuse a connection for all kinds of reasons, so the natural thing is to return a result that the caller always has to check.
1377 However, if failing to make a connection is considered an error, then a failure should throw an exception.
1379 **Exception**: 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.
1381 **Alternative**: 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:
1385 tie(val, error_code) = do_something();
1386 if (error_code == 0) {
1387 // ... handle the error or exit ...
1393 We don't consider "performance" a valid reason not to use exceptions.
1395 * Often, explicit error checking and handling consume as much time and space as exception handling.
1396 * Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
1397 * A good rule for performance critical code is to move checking outside the critical part of the code ([checking](#Rper-checking)).
1398 * In the longer term, more regular code gets better optimized.
1400 **See also**: Rule I.??? and I.??? for reporting precondition and postcondition violations.
1404 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1407 ### <a name="Ri-raw"></a> I.11: Never transfer ownership by a raw pointer (`T*`)
1411 If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
1417 X* compute(args) // don't
1424 Who deletes the returned `X`? The problem would be harder to spot if compute returned a reference.
1425 Consider returning the result by value (use move semantics if the result is large):
1427 vector<double> compute(args) // good
1429 vector<double> res(10000);
1434 **Alternative**: Pass ownership using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
1435 However that is less elegant and less efficient unless reference semantics are needed.
1437 **Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
1438 In that case, mark owning pointers using `owner`:
1440 owner<X*> compute(args) // It is now clear that ownership is transferred
1442 owner<X*> res = new X{};
1447 This tells analysis tools that `res` is an owner.
1448 That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
1450 `owner` is used similarly in the implementation of resource handles.
1452 `owner` is defined in the [Guideline Support Library](#S-gsl).
1456 Every object passed as a raw pointer (or iterator) is assumed to be owned by the caller, so that its lifetime is handled by the caller.
1458 **See also**: [Argument passing](#Rf-conventional) and [value return](#Rf-T-return).
1462 * (Simple) Warn on `delete` of a raw pointer that is not an `owner`.
1463 * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
1464 * (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
1466 ### <a name="Ri-nullptr"></a> I.12: Declare a pointer that must not be null as `not_null`
1470 To help avoid dereferencing `nullptr` errors. To improve performance by avoiding redundant checks for `nullptr`.
1474 int length(const char* p); // it is not clear whether length(nullptr) is valid
1476 length(nullptr); // OK?
1478 int length(not_null<const char*> p); // better: we can assume that p cannot be nullptr
1480 int length(const char* p); // we must assume that p can be nullptr
1482 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.
1486 The assumption that the pointer to `char` pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use `zstring` in preference to `const char*`.
1488 int length(not_null<zstring> p); // we can assume that p cannot be nullptr
1489 // we can assume that p points to a zero-terminated array of characters
1491 Note: `length()` is, of course, `std::strlen()` in disguise.
1495 * (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`.
1496 * (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`.
1498 ### <a name="Ri-array"></a> I.13: Do not pass an array as a single pointer
1502 (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.
1508 void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1510 What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
1511 What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
1512 Either is undefined behavior and a potentially very nasty bug.
1516 Consider using explicit ranges:
1518 void copy(array_view<const T> r, array_view<T> r2); // copy r to r2
1524 void draw(Shape* p, int n); // poor interface; poor code
1529 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.
1531 **Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
1533 void draw2(array_view<Circle>);
1536 draw2(array_view<Circle>(arr)); // deduce the number of elements
1537 draw2(arr); // deduce the element type and array size
1539 void draw3(array_view<Shape>);
1540 draw3(arr); // error: cannot convert Circle[10] to array_view<Shape>
1542 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 ???.
1544 **Exception**: Use `zstring` and `czstring` to represent a C-style, zero-terminated strings. But see ???.
1548 * (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.
1549 * (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.
1551 ### <a name="Ri-nargs"></a> I.14: Keep the number of function arguments low
1555 Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
1559 The standard-library `merge()` is at the limit of what we can comfortably handle
1561 template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
1562 OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
1563 InputIterator2 first2, InputIterator2 last2,
1564 OutputIterator result, Compare comp);
1566 Here, we have four template arguments and six function arguments.
1567 To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
1569 template<class InputIterator1, class InputIterator2, class OutputIterator>
1570 OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
1571 InputIterator2 first2, InputIterator2 last2,
1572 OutputIterator result);
1574 This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
1575 To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
1577 template<class InputRange1, class InputRange2, class OutputIterator>
1578 OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
1580 Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
1584 How many arguments are too many? Four arguments is a lot.
1585 There are functions that are best expressed with four individual arguments, but not many.
1587 **Alternative**: Group arguments into meaningful objects and pass the objects (by value or by reference).
1589 **Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
1593 * Warn when a functions declares two iterators (including pointers) of the same type instead of a range or a view.
1594 * (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
1596 ### <a name="Ri-unrelated"></a> I.15: Avoid adjacent unrelated parameters of the same type
1600 Adjacent arguments of the same type are easily swapped by mistake.
1606 void copy_n(T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1608 This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
1610 Use `const` for the "from" argument:
1612 void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
1616 If the order of the parameters is not important, there is no problem:
1618 int max(int a, int b);
1622 Don't pass arrays as pointers, pass an object representing a range (e.g., an `array_view`):
1624 void copy_n(array_view<const T> p, array_view<T> q); // copy from p to q
1628 (Simple) Warn if two consecutive parameters share the same type.
1630 ### <a name="Ri-abstract"></a> I.16: Prefer abstract classes as interfaces to class hierarchies
1634 Abstract classes are more likely to be stable than base classes with state.
1638 You just knew that `Shape` would turn up somewhere :-)
1640 class Shape { // bad: interface class loaded with data
1642 Point center() { return c; }
1643 virtual void draw();
1644 virtual void rotate(int);
1648 vector<Point> outline;
1652 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:
1654 class Shape { // better: Shape is a pure interface
1656 virtual Point center() = 0; // pure virtual function
1657 virtual void draw() = 0;
1658 virtual void rotate(int) = 0;
1660 // ... no data members ...
1665 (Simple) Warn if a pointer to a class `C` is assigned to a pointer to a base of `C` and the base class contains data members.
1667 ### <a name="Ri-abi"></a> I.16: If you want a cross-compiler ABI, use a C-style subset
1671 Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
1673 **Exception**: You can carefully craft an interface using a few carefully selected higher-level C++ types. See ???.
1675 **Exception**: Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
1679 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.
1683 (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
1685 # <a name="S-functions"></a> F: Functions
1687 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.
1689 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.
1690 Functions are the most critical part in most interfaces, so see the interface rules.
1692 Function rule summary:
1694 Function definition rules:
1696 * [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
1697 * [F.2: A function should perform a single logical operation](#Rf-logical)
1698 * [F.3: Keep functions short and simple](#Rf-single)
1699 * [F.4: If a function may have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
1700 * [F.5: If a function is very small and time critical, declare it inline](#Rf-inline)
1701 * [F.6: If your function may not throw, declare it `noexcept`](#Rf-noexcept)
1702 * [F.7: For general use, take `T*` arguments rather than smart pointers](#Rf-smart)
1703 * [F.8: Prefer pure functions](#Rf-pure)
1705 Argument passing rules:
1707 * [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
1708 * [F.16: Use `T*` or `owner<T*>` or a smart pointer to designate a single object](#Rf-ptr)
1709 * [F.17: Use a `not_null<T>` to indicate "null" is not a valid value](#Rf-nullptr)
1710 * [F.18: Use an `array_view<T>` or an `array_view_p<T>` to designate a half-open sequence](#Rf-range)
1711 * [F.19: Use a `zstring` or a `not_null<zstring>` to designate a C-style string](#Rf-string)
1712 * [F.20: Use a `const T&` parameter for a large object](#Rf-const-T-ref)
1713 * [F.21: Use a `T` parameter for a small object](#Rf-T)
1714 * [F.22: Use `T&` for an in-out-parameter](#Rf-T-ref)
1715 * [F.23: Use `T&` for an out-parameter that is expensive to move (only)](#Rf-T-return-out)
1716 * [F.24: Use a `TP&&` parameter when forwarding (only)](#Rf-pass-ref-ref)
1717 * [F.25: Use a `T&&` parameter together with `move` for rare optimization opportunities](#Rf-pass-ref-move)
1718 * [F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
1719 * [F.27: Use a `shared_ptr<T>` to share ownership](#Rf-shared_ptr)
1723 * [F.40: Prefer return values to out-parameters](#Rf-T-return)
1724 * [F.41: Prefer to return tuples to multiple out-parameters](#Rf-T-multi)
1725 * [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
1726 * [F.43: Never (directly or indirectly) return a pointer to a local object](#Rf-dangle)
1727 * [F.44: Return a `T&` when "returning no object" isn't an option](#Rf-return-ref)
1728 * [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
1730 Other function rules:
1732 * [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)
1733 * [F.51: Prefer overloading over default arguments for virtual functions](#Rf-default-args)
1734 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
1735 * [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)
1737 Functions have strong similarities to lambdas and function objects so see also Section ???.
1739 ## <a name="SS-fct-def"></a> F.def: Function definitions
1741 A function definition is a function declaration that also specifies the function's implementation, the function body.
1743 ### <a name="Rf-package"></a> F.1: "Package" meaningful operations as carefully named functions
1747 Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
1748 If something is a well-specified action, separate it out from its surrounding code and give it a name.
1750 ##### Example, don't
1752 void read_and_print(istream& is) // read and print an int
1756 cout << "the int is " << x << '\n';
1758 cerr << "no int on input\n";
1761 Almost everything is wrong with `read_and_print`.
1762 It reads, it writes (to a fixed `ostream`), it writes error messages (to a fixed `ostream`), it handles only `int`s.
1763 There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
1764 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
1765 mess could become hard to understand.
1769 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.
1773 sort(a, b, [](T x, T y) { return x.valid() && y.valid() && x.value() < y.value(); });
1775 Naming that lambda breaks up the expression into its logical parts and provides a strong hint to the meaning of the lambda.
1777 auto lessT = [](T x, T y) { return x.valid() && y.valid() && x.value() < y.value(); };
1780 find_if(a, b, lessT);
1782 The shortest code is not always the best for performance or maintainability.
1784 **Exception**: Loop bodies, including lambdas used as loop bodies, rarely need to be named.
1785 However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
1786 The rule [Keep functions short](#Rf-single) implies "Keep loop bodies short."
1787 Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be re-usable.
1791 * See [Keep functions short](#Rf-single)
1792 * Flag identical and very similar lambdas used in different places.
1794 ### <a name="Rf-logical"></a> F.2: A function should perform a single logical operation
1798 A function that performs a single operation is simpler to understand, test, and reuse.
1804 void read_and_print() // bad
1812 This is a monolith that is tied to a specific input and will never find a another (different) use. Instead, break functions up into suitable logical parts and parameterize:
1814 int read(istream& is) // better
1822 void print(ostream& os, int x)
1827 These can now be combined where needed:
1829 void read_and_print()
1835 If there was a need, we could further templatize `read()` and `print()` on the data type, the I/O mechanism, etc. Example:
1837 auto read = [](auto& input, auto& value) // better
1843 auto print(auto& output, const auto& value)
1845 output << value << "\n";
1850 * Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
1851 * Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
1852 * Consider functions with 7 or more parameters suspicious.
1854 ### <a name="Rf-single"></a> F.3: Keep functions short and simple
1858 Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
1859 Functions with complex control structures are more likely to be long and more likely to hide logical errors
1865 double simpleFunc(double val, int flag1, int flag2)
1866 // simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags.
1869 double intermediate;
1871 intermediate = func1(val);
1873 intermediate = sqrt(intermediate);
1875 else if (flag1 == -1) {
1876 intermediate = func1(-val);
1878 intermediate = sqrt(-intermediate);
1881 if (abs(flag2) > 10) {
1882 intermediate = func2(intermediate);
1884 switch (flag2 / 10) {
1885 case 1: if (flag1 == -1) return finalize(intermediate, 1.171); break;
1886 case 2: return finalize(intermediate, 13.1);
1889 return finalize(intermediate, 0.);
1892 This is too complex (and also pretty long).
1893 How would you know if all possible alternatives have been correctly handled?
1894 Yes, it breaks other rules also.
1898 double func1_muon(double val, int flag)
1903 double funct1_tau(double val, int flag1, int flag2)
1908 double simpleFunc(double val, int flag1, int flag2)
1909 // simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags.
1912 return func1_muon(val, flag2);
1914 return func1_tau(-val, flag1, flag2); // handled by func1_tau: flag1 = -flag1;
1920 "It doesn't fit on a screen" is often a good practical definition of "far too large."
1921 One-to-five-line functions should be considered normal.
1925 Break large functions up into smaller cohesive and named functions.
1926 Small simple functions are easily inlined where the cost of a function call is significant.
1930 * Flag functions that do not "fit on a screen."
1931 How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
1932 * Flag functions that are too complex. How complex is too complex?
1933 You could use cyclomatic complexity. Try "more that 10 logical path through." Count a simple switch as one path.
1935 ### <a name="Rf-constexpr"></a> F.4: If a function may have to be evaluated at compile time, declare it `constexpr`
1939 `constexpr` is needed to tell the compiler to allow compile-time evaluation.
1943 The (in)famous factorial:
1945 constexpr int fac(int n)
1947 constexpr int max_exp = 17; // constexpr enables this to be used in Expects
1948 Expects(0 <= n && n < max_exp); // prevent silliness and overflow
1950 for (int i = 2; i <= n; ++i) x *= i;
1954 This is C++14. For C++11, use a recursive formulation of `fac()`.
1958 `constexpr` does not guarantee compile-time evaluation;
1959 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.
1961 constexpr int min(int x, int y) { return x < y ? x : y;}
1965 int m1 = min(-1, 2); // probably compile-time evaluation
1966 constexpr int m2 = min(-1, 2); // compile-time evaluation
1967 int m3 = min(-1, v); // run-time evaluation
1968 constexpr int m4 = min(-1, v); // error: cannot evaluate at compile-time
1973 `constexpr` functions are pure: they can have no side effects.
1976 constexpr int double(int v)
1978 ++dcount; // error: attempted side effect from constexpr function
1982 This is usually a very good thing.
1986 Don't try to make all functions `constexpr`. Most computation is best done at run time.
1990 Impossible and unnecessary.
1991 The compiler gives an error if a non-`constexpr` function is called where a constant is required.
1993 ### <a name="Rf-inline"></a> F.5: If a function is very small and time critical, declare it `inline`
1997 Some optimizers are good at inlining without hints from the programmer, but don't rely on it.
1998 Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
1999 We are still waiting.
2000 Specifying `inline` encourages the compiler to do a better job.
2002 **Exception**: Do not put an `inline` function in what is meant to be a stable interface unless you are really sure that it will not change.
2003 An inline function is part of the ABI.
2007 `constexpr` implies `inline`.
2011 Member functions defined in-class are `inline` by default.
2013 **Exception**: Template functions (incl. template member functions) must be in headers and therefore inline.
2017 Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions).
2018 To fix: Declare the function out of line. (NM: Certainly possible, but size-based metrics can be very annoying.)
2020 ### <a name="Rf-noexcept"></a> F.6: If your function may not throw, declare it `noexcept`
2024 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.
2028 Put `noexcept` on every function written completely in C or in any other language without exceptions.
2029 The C++ standard library does that implicitly for all functions in the C standard library.
2033 `constexpr` functions cannot throw, so you don't need to use `noexcept` for those.
2037 You can use `noexcept` even on functions that can throw:
2039 vector<string> collect(istream& is) noexcept
2042 for (string s; is >> s;)
2047 If `collect()` runs out of memory, the program crashes.
2048 Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do;
2049 `terminate()` may generate suitable error log information (but after memory runs out it is hard to do anything clever).
2053 In most programs, most functions can throw
2054 (e.g., because they use `new`, call functions that do, or use library functions that reports failure by throwing), so don't just sprinkle `noexcept` all over the place.
2055 `noexcept` is most useful for frequently used, low-level functions.
2059 Destructors, `swap` functions, move operations, and default constructors should never throw.
2063 * Flag functions that are not `noexcept`, yet cannot throw.
2064 * Flag throwing `swap`, `move`, destructors, and default constructors.
2066 ### <a name="Rf-smart"></a> F.7: For general use, take `T*` arguments rather than smart pointers
2070 Passing a smart pointer transfers or shares ownership.
2071 Passing by smart pointer restricts the use of a function to callers that use smart pointers.
2072 Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
2076 void f(int*); // accepts any int*
2077 void g(unique_ptr<int>); // can only accept ints for which you want to transfer ownership
2078 void g(shared_ptr<int>); // can only accept ints for which you are willing to share ownership
2082 We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.
2084 **See also**: Discussion of [smart pointer use](#Rr-summary-smartptrs).
2088 Flag smart pointer arguments.
2090 ### <a name="Rf-pure"></a> F.8: Prefer pure functions
2094 Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
2099 auto square(T t) { return t * t; }
2103 `constexpr` functions are pure.
2109 ## <a name="SS-call"></a> F.call: Argument passing
2111 There are a variety of ways to pass arguments to a function and to return values.
2113 ### <a name="Rf-conventional"></a> Rule F.15: Prefer simple and conventional ways of passing information
2117 Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
2118 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.
2120 ![Normal parameter passing table](./param-passing-normal.png "Normal parameter passing")
2122 **For an "output-only" value:** Prefer return values to output parameters.
2123 This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
2124 If you have multiple values to return, [use a tuple](#Rf-T-multi) or similar multi-member type.
2128 vector<const int*> find_all(const vector<int>&, int x); // return pointers to elements with the value x
2132 void find_all(const vector<int>&, vector<const int*>& out, int x); // place pointers to elements with value x in out
2136 * For non-value types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
2137 * 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 non-`const` reference to a target object to fill (to be used as an out-parameter).
2138 * In the special case of allowing a caller 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 instead and pass by `&`. This is one use of the more generally named "caller-allocated out" pattern.
2140 **For an "in-out" parameter:** Pass by non-`const` reference. This makes it clear to callers that the object is assumed to be modified.
2142 **For an "input-only" value:** If the object is cheap to copy, pass by value.
2143 Otherwise, pass by `const&`. It is useful to know that a function does not mutate an argument, and both allow initialization by rvalues.
2144 What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
2145 In particular, an object passed by value does not require an extra reference to access from the function.
2147 ![Advanced parameter passing table](./param-passing-advanced.png "Advanced parameter passing")
2149 For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
2151 * If the function is going to unconditionally move from the argument, take it by `&&`.
2152 * If the function is going to keep a copy of the argument, in addition to passing by `const&` add an overload that passes the parameter by `&&` and in the body `std::move`s it to its destination. (See [F.25](#Rf-pass-ref-move).)
2153 * In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. (See [F.24](#Rf-pass-ref-ref).)
2157 int multiply(int, int); // just input ints, pass by value
2159 string& concatenate(string&, const string& suffix); // suffix is input-only but not as cheap as an int, pass by const&
2161 void sink(unique_ptr<widget>); // input only, and consumes the widget
2163 Avoid "esoteric techniques" such as:
2165 * Passing arguments as `T&&` "for efficiency". Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.25](#Rf-pass-ref-move).)
2166 * Returning `const T&` from assignments and similar operations.
2170 Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`.
2172 Matrix operator+(const Matrix& a, const Matrix& b)
2175 // ... fill res with the sum ...
2179 Matrix x = m1 + m2; // move constructor
2181 y = m3 + m3; // move assignment
2185 The (optional) return value optimization doesn't handle the assignment case.
2187 **See also**: [implicit arguments](#Ri-explicit).
2191 This is a philosophical guideline that is infeasible to check directly and completely.
2192 However, many of the detailed rules (F.16-F.45) can be checked, such as passing a `const int&`, returning an `array<BigPOD>` by value, and returning a pointer to free store alloced by the function.
2194 ### <a name="Rf-ptr"></a> F.16: Use `T*` or `owner<T*>` to designate a single object
2198 In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as:
2200 * Identify a (single) object (not to be deleted by this function)
2201 * Point to an object allocated on the free store (and delete it later)
2202 * Hold the `nullptr`
2203 * Identify a C-style string (zero-terminated array of characters)
2204 * Identify an array with a length specified separately
2205 * Identify a location in an array
2207 For example, `not_null<T*>` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
2208 Additionally, when debugging, `owner<T*>` and `not_null<T>` can be instrumented to check for correctness.
2214 int length(Record* p);
2216 When I call `length(r)` should I test for `r == nullptr` first? Should the implementation of `length()` test for `p == nullptr`?
2218 int length(not_null<Record*> p); // it is the caller's job to make sure p != nullptr
2220 int length(Record* p); // the implementor of length() must assume that p == nullptr is possible
2224 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).
2228 `owner<T*>` represents ownership.
2230 **Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr<T>`) points to a single element.
2232 **See also**: [Support library](#S-gsl).
2236 * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
2238 ### <a name="Rf-nullptr"></a> F.17: Use a `not_null<T>` to indicate that "null" is not a valid value
2242 Clarity. Making it clear that a test for null isn't needed.
2246 not_null<T*> check(T* p) { if (p) return not_null<T*>{p}; throw Unexpected_nullptr{}; }
2248 void computer(not_null<array_view<int>> p)
2250 if (0 < p.size()) { // bad: redundant test
2257 `not_null` is not just for built-in pointers. It works for `array_view`, `string_view`, `unique_ptr`, `shared_ptr`, and other pointer-like types.
2261 * (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.
2262 * (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
2263 * (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
2265 ### <a name="Rf-range"></a> F.18: Use an `array_view<T>` or an `array_view_p<T>` to designate a half-open sequence
2269 Informal/non-explicit ranges are a source of errors.
2273 X* find(array_view<X> r, const X& v); // find v in r
2277 auto p = find({vec.begin(), vec.end()}, X{}); // find X{} in vec
2281 Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure. In particular, given a pair of arguments `(p, n)` designating an array [`p`:`p+n`), it is in general impossible to know if there really are n elements to access following `*p`. `array_view<T>` and `array_view_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.
2285 An `array_view<T>` object does not own its elements and is so small that it can be passed by value.
2289 Passing an `array_view` object as an argument is exactly as efficient as passing a pair of pointer arguments or passing a pointer and an integer count.
2291 **See also**: [Support library](#S-gsl).
2295 (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `array_view` instead.
2297 ### <a name="Rf-string"></a> F.19: Use a `zstring` or a `not_null<zstring>` to designate a C-style string
2301 C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters.
2302 We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.
2308 int length(const char* p);
2310 When I call `length(s)` should I test for `s == nullptr` first? Should the implementation of `length()` test for `p == nullptr`?
2312 int length(zstring p); // the implementor of length() must assume that p == nullptr is possible
2314 int length(not_null<zstring> p); // it is the caller's job to make sure p != nullptr
2318 `zstring` do not represent ownership.
2320 **See also**: [Support library](#S-gsl).
2322 ### <a name="Rf-const-T-ref"></a> F.20: Use a `const T&` parameter for a large object
2326 Copying large objects can be expensive. A `const T&` is always cheap and protects the caller from unintended modification.
2330 void fct(const string& s); // OK: pass by const reference; always cheap
2332 void fct2(string s); // bad: potentially expensive
2334 **Exception**: Sinks (that is, a function that eventually destroys an object or passes it along to another sink), may benefit ???
2338 A reference may be assumed to refer to a valid object (language rule).
2339 There is no (legitimate) "null reference."
2340 If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
2344 * (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `4*sizeof(int)`.
2345 Suggest using a `const` reference instead.
2347 ### <a name="Rf-T"></a> F.21: Use a `T` parameter for a small object
2351 Nothing beats the simplicity and safety of copying.
2352 For small objects (up to two or three words) it is also faster than alternatives.
2356 void fct(int x); // OK: Unbeatable
2358 void fct2(const int& x); // bad: overhead on access in fct2()
2360 void fct(int& x); // OK, but means something else; use only for an "out parameter"
2364 * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference has a size less than `3*sizeof(int)`. Suggest passing by value instead.
2366 ### <a name="Rf-T-ref"></a> F.22: Use a `T&` for an in-out-parameter
2370 A called function can write to a non-`const` reference argument, so assume that it does.
2374 void update(Record& r); // assume that update writes to r
2378 A `T&` argument can pass information into a function as well as well as out of it.
2379 Thus `T&` could be and in-out-parameter. That can in itself be a problem and a source of errors:
2383 s = "New York"; // non-obvious error
2388 string buffer = ".................................";
2393 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).
2394 If the writer of `g()` makes an assumption about the size of `buffer` a bad logic error can happen.
2398 * (Moderate) ((Foundation)) Warn about functions with non-`const` reference arguments that do *not* write to them.
2399 * Flag functions that take a `T&` and replace the `T` referred to, rather what the contents of that `T`
2401 ### <a name="Rf-T-return-out"></a> F.23: Use `T&` for an out-parameter that is expensive to move (only)
2405 A return value is harder to miss and harder to misuse than a `T&` (an in-out parameter); [see also](#Rf-T-return); [see also](#Rf-T-multi).
2411 char load[2024 - 16];
2414 Package fill(); // Bad: large return value
2415 void fill(Package&); // OK
2418 void val(int&); // Bad: Is val reading its argument
2422 Hard to choose a cutover value for the size of the value returned.
2424 ### <a name="Rf-pass-ref-ref"></a> F.24: Use a `TP&&` parameter when forwarding (only)
2428 When `TP` is a template type parameter, `TP&&` is a forwarding reference -- it both *ignores* and *preserves* const-ness and rvalue-ness. Therefore any code that uses a `T&&` 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.
2432 template <class F, class... Args>
2433 inline auto invoke(F&& f, Args&&... args) {
2434 return forward<F>(f)(forward<Args>(args)...);
2439 Flag a function that takes a `TP&&` parameter (where `TP` is a template type parameter name) and uses it without `std::forward`.
2441 ### <a name="Rf-pass-ref-move"></a> F.25: Use a `T&&` parameter together with `move` for rare optimization opportunities
2445 Moving from an object leaves an object in its moved-from state behind.
2446 In general, moved-from objects are dangerous. The only guaranteed operation is destruction (more generally, member functions without preconditions).
2447 The standard library additionally requires that a moved-from object can be assigned to.
2448 If you have performance justification to optimize for rvalues, overload on `&&` and then `move` from the parameter ([example of such overloading](#)).
2452 void somefct(string&&);
2456 string s = "this is going to be fun!";
2458 somefct(std::move(s)); // we don't need s any more, give it to somefct()
2460 cout << s << '\n'; // Oops! What happens here?
2465 * Flag all `X&&` parameters (where `X` is not a template type parameter name) and code that uses them without `std::move`.
2466 * Flag access to moved-from objects.
2468 ### <a name="Rf-unique_ptr"></a> F.26: Use a `unique_ptr<T>` to transfer ownership where a pointer is needed
2472 Using `unique_ptr` is the cheapest way to pass a pointer safely.
2476 unique_ptr<Shape> get_shape(istream& is) // assemble shape from input stream
2478 auto kind = read_header(is); // read header and identify the next shape on input
2481 return make_unique<Circle>(is);
2483 return make_unique<Triangle>(is);
2490 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).
2494 (Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead.
2496 ### <a name="Rf-shared_ptr"></a> F.27: Use a `shared_ptr<T>` to share ownership
2500 Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object.
2504 shared_ptr<Image> im { read_image(somewhere) };
2506 std::thread t0 {shade, args0, top_left, im};
2507 std::thread t1 {shade, args1, top_right, im};
2508 std::thread t2 {shade, args2, bottom_left, im};
2509 std::thread t3 {shade, args3, bottom_right, im};
2512 // last thread to finish deletes the image
2516 Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time.
2517 `shared_ptr` is for shared ownership.
2519 **Alternative**: Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.
2523 (Not enforceable) This is a too complex pattern to reliably detect.
2525 ### <a name="Rf-T-return"></a> F.40: Prefer return values to out-parameters
2529 It's self-documenting. A `&` parameter could be either in/out or out-only.
2542 Flag non-const reference parameters that are not read before being written to and are a type that could be cheaply returned.
2544 ### <a name="Rf-T-multi"></a> F.41: Prefer to return tuples to multiple out-parameters
2548 A return value is self-documenting as an "output-only" value.
2549 And yes, C++ does have multiple return values, by convention of using a `tuple`, with the extra convenience of `tie` at the call site.
2553 int f(const string& input, /*output only*/ string& output_data) // BAD: output-only parameter documented in a comment
2556 output_data = something();
2560 tuple<int, string> f(const string& input) // GOOD: self-documenting
2563 return make_tuple(something(), status);
2566 In fact, C++98's standard library already used this convenient feature, because a `pair` is like a two-element `tuple`.
2567 For example, given a `set<string> myset`, consider:
2570 result = myset.insert("Hello");
2571 if (result.second) do_something_with(result.first); // workaround
2573 With C++11 we can write this, putting the results directly in existing local variables:
2575 Sometype iter; // default initialize if we haven't already
2576 Someothertype success; // used these variables for some other purpose
2578 tie(iter, success) = myset.insert("Hello"); // normal return value
2579 if (success) do_something_with(iter);
2581 **Exception**: For types like `string` and `vector` that carry additional capacity, it can sometimes be useful to treat it as in/out instead by using the "caller-allocated out" pattern, which is to pass an output-only object by reference to non-`const` so that when the callee writes to it the object can reuse any capacity or other resources that it already contains. This technique can dramatically reduce the number of allocations in a loop that repeatedly calls other functions to get string values, by using a single string object for the entire loop.
2585 In some cases it may be useful to return a specific, user-defined `Value_or_error` type along the lines of `variant<T, error_code>`, rather than using the generic `tuple`.
2589 * Output parameters should be replaced by return values.
2590 An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
2592 ### <a name="Rf-return-ptr"></a> F.42: Return a `T*` to indicate a position (only)
2596 That's what pointers are good for.
2597 Returning a `T*` to transfer ownership is a misuse.
2601 Do not return a pointer to something that is not in the caller's scope.
2605 Node* find(Node* t, const string& s) // find s in a binary tree of Nodes
2607 if (t == nullptr || t->name == s) return t;
2608 if (auto p = find(t->left, s)) return p;
2609 if (auto p = find(t->right, s)) return p;
2613 If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`.
2614 Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.
2618 Positions can also be transferred by iterators, indices, and references.
2626 return &x; // Bad: returns pointer to object that is about to be destroyed
2629 This applies to references as well:
2635 return x; // Bad: returns reference to object that is about to be destroyed
2638 **See also**: [discussion of dangling pointer prevention](#???).
2642 A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.
2644 * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
2645 * Static analysis can catch most (all?) common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)
2647 ### <a name="Rf-dangle"></a> F.43: Never (directly or indirectly) return a pointer to a local object
2651 To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
2655 After the return from a function its local objects no longer exist:
2663 void g(int* p) // looks innocent enough
2666 cout << "*p == " << *p << '\n';
2668 cout << "gx == " << gx << '\n';
2674 int z = *p; // read from abandoned stack frame (bad)
2675 g(p); // pass pointer to abandoned stack frame to function (bad)
2678 Here on one popular implementation I got the output:
2683 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`.
2685 Imagine what would happen if `fx` and `gx` were of different types.
2686 Imagine what would happen if `fx` or `gx` was a type with an invariant.
2687 Imagine what would happen if more that dangling pointer was passed around among a larger set of functions.
2688 Imagine what a cracker could do with that dangling pointer.
2690 Fortunately, most (all?) modern compilers catch and warn against this simple case.
2694 You can construct similar examples using references.
2698 This applies only to non-`static` local variables.
2699 All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.
2703 Not all examples of leaking a pointer to a local variable are that obvious:
2705 int* glob; // global variables are bad in so many ways
2716 steal([&] { return &i; });
2722 cout << *glob << '\n';
2725 Here I managed to read the location abandoned by the call of `f`.
2726 The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways.
2730 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.
2734 Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one;
2735 such examples are handled equivalently to leaks of pointers out of a function.
2737 **See also**: Another way of getting dangling pointers is [pointer invalidation](#???).
2738 It can be detected/prevented with similar techniques.
2742 Preventable through static analysis.
2744 ### <a name="Rf-return-ref"></a> F.44: Return a `T&` when "returning no object" isn't an option
2748 The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary.
2750 **See also**: The return of a reference must not imply transfer of ownership:
2751 [discussion of dangling pointer prevention](#???) and [discussion of ownership](#???).
2761 ### <a name="Rf-return-ref-ref"></a> F.45: Don't return a `T&&`
2765 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 [F54](#Rf-local-ref-ref).
2767 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&&`).
2771 If `F` returns by value, this function returns a reference to a temporary.
2776 log_call(typeid(f)); // or whatever instrumentation
2787 log_call(typeid(f)); // or whatever instrumentation
2791 **Exception**: `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 `&&`.
2795 Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
2797 ### <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)
2801 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.
2805 // writing a function that should only take an int or a string -- overloading is natural
2807 void f(const string&);
2809 // writing a function object that needs to capture local state and appear
2810 // at statement or expression scope -- a lambda is natural
2811 vector<work> v = lots_of_work();
2812 for (int tasknum = 0; tasknum < max; ++tasknum) {
2816 ... process 1/max-th of v, the tasknum-th chunk
2823 **Exception**: 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.
2827 * 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.
2829 ### <a name="Rf-default-args"></a> F.51: Prefer overloading over default arguments for virtual functions
2831 ??? possibly other situations?
2835 Virtual function overrides do not inherit default arguments, leading to surprises.
2841 virtual int multiply(int value, int factor = 2) = 0;
2844 class derived : public base {
2846 int multiply(int value, int factor = 10) override;
2852 b.multiply(10); // these two calls will call the same function but
2853 d.multiply(10); // with different arguments and so different results
2857 Flag all uses of default arguments in virtual functions.
2859 ### <a name="Rf-reference-capture"></a> F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms
2863 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.
2867 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.
2869 void send_packets(buffers& bufs)
2871 stage encryptor ([] (buffer& b){ encrypt(b); });
2872 stage compressor ([&](buffer& b){ compress(b); encryptor.process(b); });
2873 stage decorator ([&](buffer& b){ decorate(b); compressor.process(b); });
2874 for (auto& b : bufs) { decorator.process(b); }
2875 } // automatically blocks waiting for pipeline to finish
2881 ### <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
2885 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.
2892 // a, b, c are local variables
2893 background_thread.queue_work([=]{ process(a, b, c); }); // want copies of a, b, and c
2900 # <a name="S-class"></a> C: Classes and Class Hierarchies
2902 A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces.
2903 Class hierarchies are used to organize related classes into hierarchical structures.
2907 * [C.1: Organize related data into structures (`struct`s or `class`es)](#Rc-org)
2908 * [C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently](#Rc-struct)
2909 * [C.3: Represent the distinction between an interface and an implementation using a class](#Rc-interface)
2910 * [C.4: Make a function a member only if it needs direct access to the representation of a class](#Rc-member)
2911 * [C.5: Place helper functions in the same namespace as the class they support](#Rc-helper)
2912 * [C.6: Declare a member function that does not modify the state of its object `const`](#Rc-const)
2916 * [C.concrete: Concrete types](#SS-concrete)
2917 * [C.ctor: Constructors, assignments, and destructors](#SS-ctor)
2918 * [C.con: Containers and other resource handles](#SS-containers)
2919 * [C.lambdas: Function objects and lambdas](#SS-lambdas)
2920 * [C.hier: Class hierarchies (OOP)](#SS-hier)
2921 * [C.over: Overloading and overloaded operators](#SS-overload)
2922 * [C.union: Unions](#SS-union)
2924 ### <a name="Rc-org"></a> C.1: Organize related data into structures (`struct`s or `class`es)
2928 Ease of comprehension. If data is related (for fundamental reasons), that fact should be reflected in code.
2932 void draw(int x, int y, int x2, int y2); // BAD: unnecessary implicit relationships
2933 void draw(Point from, Point to); // better
2937 A simple class without virtual functions implies no space or time overhead.
2941 From a language perspective `class` and `struct` differ only in the default visibility of their members.
2945 Probably impossible. Maybe a heuristic looking for data items used together is possible.
2947 ### <a name="Rc-struct"></a> C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently
2951 Ease of comprehension. The use of `class` alerts the programmer to the need for an invariant.
2955 An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using `Expects`.
2959 struct Pair { // the members can vary independently
2972 Date(int yy, Month mm, char dd); // validate that {yy, mm, dd} is a valid date and initialize
2978 Look for `struct`s with all data private and `class`es with public members.
2980 ### <a name="Rc-interface"></a> C.3: Represent the distinction between an interface and an implementation using a class
2984 An explicit distinction between interface and implementation improves readability and simplifies maintenance.
2989 // ... some representation ...
2992 Date(int yy, Month mm, char dd); // validate that {yy, mm, dd} is a valid date and initialize
2995 Month month() const;
2999 For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though).
3003 Using a class in this way to represent the distinction between interface and implementation is of course not the only way.
3004 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.
3005 The most important issue is to explicitly distinguish between an interface and its implementation "details."
3006 Ideally, and typically, an interface is far more stable than its implementation(s).
3012 ### <a name="Rc-member"></a> C.4: Make a function a member only if it needs direct access to the representation of a class
3016 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.
3021 // ... relatively small interface ...
3024 // helper functions:
3025 Date next_weekday(Date);
3026 bool operator==(Date, Date);
3028 The "helper functions" have no need for direct access to the representation of a `Date`.
3032 This rule becomes even better if C++17 gets "uniform function call." ???
3036 Look for member function that do not touch data members directly.
3037 The snag is that many member functions that do not need to touch data members directly do.
3039 ### <a name="Rc-helper"></a> C.5: Place helper functions in the same namespace as the class they support
3043 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.
3044 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.
3048 namespace Chrono { // here we keep time-related services
3050 class Time { /* ... */ };
3051 class Date { /* ... */ };
3053 // helper functions:
3054 bool operator==(Date, Date);
3055 Date next_weekday(Date);
3061 * Flag global functions taking argument types from a single namespace.
3063 ### <a name="Rc-const"></a> C.6: Declare a member function that does not modify the state of its object `const`
3067 More precise statement of design intent, better readability, more errors caught by the compiler, more optimization opportunities.
3071 int Date::day() const { return d; }
3075 [Do not cast away `const`](#Res-casts-const).
3079 Flag non-`const` member functions that do not write to their objects
3081 ## <a name="SS-concrete"></a> C.concrete: Concrete types
3083 One ideal for a class is to be a regular type.
3084 That means roughly "behaves like an `int`." A concrete type is the simplest kind of class.
3085 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.
3086 If a concrete type has both `=` and `==`, `a=b` should result in `a == b` being `true`.
3087 Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
3088 The C++ built-in types are regular, and so are standard-library classes, such as `string`, `vector`, and `map`.
3089 Concrete types are also often referred to as value types to distinguish them from types uses as part of a hierarchy.
3091 Concrete type rule summary:
3093 * [C.10: Prefer a concrete type over more complicated classes](#Rc-concrete)
3094 * [C.11: Make concrete types regular](#Rc-regular)
3096 ### <a name="Rc-concrete"></a> C.10 Prefer a concrete type over more complicated classes
3100 A concrete type is fundamentally simpler than a hierarchy:
3101 easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.
3102 You need a reason (use cases) for using a hierarchy.
3108 // ... operations ...
3109 // .. no virtual functions ...
3114 // ... operations, some virtual ...
3120 Point1 p11 {1, 2}; // make an object on the stack
3121 Point1 p12 {p11}; // a copy
3123 auto p21 = make_unique<Point2>(1, 2); // make an object on the free store
3124 auto p22 = p21.clone(); // make a copy
3129 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.
3130 That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.
3134 Concrete types can be stack allocated and be members of other classes.
3138 The use of indirection is fundamental for run-time polymorphic interfaces.
3139 The allocation/deallocation overhead is not (that's just the most common case).
3140 We can use a base class as the interface of a scoped object of a derived class.
3141 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.
3147 ### <a name="Rc-regular"></a> C.11: Make concrete types regular
3151 Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
3160 bool operator==(const Bundle& a, const Bundle& b) { return a.name == b.name && a.vr == b.vr; }
3162 Bundle b1 { "my bundle", {r1, r2, r3}};
3164 if (!(b1 == b2)) error("impossible!");
3165 b2.name = "the other bundle";
3166 if (b1 == b2) error("No!");
3168 In particular, if a concrete type has an assignment also give it an equals operator so that `a=b` implies `a == b`.
3174 ## <a name="SS-ctor"></a> C.ctor: Constructors, assignments, and destructors
3176 These functions control the lifecycle of objects: creation, copy, move, and destruction.
3177 Define constructors to guarantee and simplify initialization of classes.
3179 These are *default operations*:
3181 * a default constructor: `X()`
3182 * a copy constructor: `X(const X&)`
3183 * a copy assignment: `operator=(const X&)`
3184 * a move constructor: `X(X&&)`
3185 * a move assignment: `operator=(X&&)`
3186 * a destructor: `~X()`
3188 By default, the compiler defines each of these operations if it is used, but the default can be suppressed.
3190 The default operations are a set of related operations that together implement the lifecycle semantics of an object.
3191 By default, C++ treats classes as value-like types, but not all types are value-like.
3193 Set of default operations rules:
3195 * [C.20: If you can avoid defining any default operations, do](#Rc-zero)
3196 * [C.21: If you define or `=delete` any default operation, define or `=delete` them all](#Rc-five)
3197 * [C.22: Make default operations consistent](#Rc-matched)
3201 * [C.30: Define a destructor if a class needs an explicit action at object destruction](#Rc-dtor)
3202 * [C.31: All resources acquired by a class must be released by the class's destructor](#Rc-dtor-release)
3203 * [C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning](#Rc-dtor-ptr)
3204 * [C.33: If a class has an owning pointer member, define or `=delete` a destructor](#Rc-dtor-ptr2)
3205 * [C.34: If a class has an owning reference member, define or `=delete` a destructor](#Rc-dtor-ref)
3206 * [C.35: A base class with a virtual function needs a virtual destructor](#Rc-dtor-virtual)
3207 * [C.36: A destructor may not fail](#Rc-dtor-fail)
3208 * [C.37: Make destructors `noexcept`](#Rc-dtor-noexcept)
3212 * [C.40: Define a constructor if a class has an invariant](#Rc-ctor)
3213 * [C.41: A constructor should create a fully initialized object](#Rc-complete)
3214 * [C.42: If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
3215 * [C.43: Give a class a default constructor](#Rc-default0)
3216 * [C.44: Prefer default constructors to be simple and non-throwing](#Rc-default00)
3217 * [C.45: Don't define a default constructor that only initializes data members; use member initializers instead](#Rc-default)
3218 * [C.46: By default, declare single-argument constructors `explicit`](#Rc-explicit)
3219 * [C.47: Define and initialize member variables in the order of member declaration](#Rc-order)
3220 * [C.48: Prefer in-class initializers to member initializers in constructors for constant initializers](#Rc-in-class-initializer)
3221 * [C.49: Prefer initialization to assignment in constructors](#Rc-initialize)
3222 * [C.50: Use a factory function if you need "virtual behavior" during initialization](#Rc-factory)
3223 * [C.51: Use delegating constructors to represent common actions for all constructors of a class](#Rc-delegating)
3224 * [C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization](#Rc-inheriting)
3226 Copy and move rules:
3228 * [C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`](#Rc-copy-assignment)
3229 * [C.61: A copy operation should copy](#Rc-copy-semantic)
3230 * [C.62: Make copy assignment safe for self-assignment](#Rc-move-self)
3231 * [C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`](#Rc-move-assignment)
3232 * [C.64: A move operation should move and leave its source in a valid state](#Rc-move-semantic)
3233 * [C.65: Make move assignment safe for self-assignment](#Rc-copy-self)
3234 * [C.66: Make move operations `noexcept`](#Rc-move-noexcept)
3235 * [C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired](#Rc-copy-virtual)
3237 Other default operations rules:
3239 * [C.80: Use `=default` if you have to be explicit about using the default semantics](#Rc-=default)
3240 * [C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)](#Rc-=delete)
3241 * [C.82: Don't call virtual functions in constructors and destructors](#Rc-ctor-virtual)
3242 * [C.83: For value-like types, consider providing a `noexcept` swap function](#Rc-swap)
3243 * [C.84: A `swap` may not fail](#Rc-swap-fail)
3244 * [C.85: Make `swap` `noexcept`](#Rc-swap-noexcept)
3245 * [C.86: Make `==` symmetric with respect of operand types and `noexcept`](#Rc-eq)
3246 * [C.87: Beware of `==` on base classes](#Rc-eq-base)
3247 * [C.88: Make `<` symmetric with respect of operand types and `noexcept`](#Rc-lt)
3248 * [C.89: Make a `hash` `noexcept`](#Rc-hash)
3250 ## <a name="SS-defop"></a> C.defop: Default Operations
3252 By default, the language supply the default operations with their default semantics.
3253 However, a programmer can disable or replace these defaults.
3255 ### <a name="Rc-zero"></a> C.20: If you can avoid defining default operations, do
3259 It's the simplest and gives the cleanest semantics.
3265 // ... no default operations declared ...
3271 Named_map nm; // default construct
3272 Named_map nm2 {nm}; // copy construct
3274 Since `std::map` and `string` have all the special functions, no further work is needed.
3278 This is known as "the rule of zero".
3282 (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
3283 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`.
3285 ### <a name="Rc-five"></a> C.21: If you define or `=delete` any default operation, define or `=delete` them all
3289 The semantics of the special functions are closely related, so it one needs to be non-default, the odds are that other need modification.
3293 struct M2 { // bad: incomplete set of default operations
3296 // ... no copy or move operations ...
3297 ~M2() { delete[] rep; }
3299 pair<int, int>* rep; // zero-terminated set of pairs
3307 x = y; // the default assignment
3311 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).
3315 This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor.
3319 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.
3320 If you don't want a default operation, suppress it with `=delete`.
3324 Compilers enforce much of this rule and ideally warn about any violation.
3328 Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
3332 (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions.
3334 ### <a name="Rc-matched"></a> C.22: Make default operations consistent
3338 The default operations are conceptually a matched set. Their semantics are interrelated.
3339 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.
3343 class Silly { // BAD: Inconsistent copy operations
3349 Silly(const Silly& a) : p{a.p} { *p = *a.p; } // deep copy
3350 Silly& operator=(const Silly& a) { p = a.p; } // shallow copy
3354 These operations disagree about copy semantics. This will lead to confusion and bugs.
3358 * (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.
3359 * (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
3360 * (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
3361 * (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
3363 ## <a name="SS-dtor"></a> C.dtor: Destructors
3365 "Does this class need a destructor?" is a surprisingly powerful design question.
3366 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);
3367 that is, its members can take care of themselves as concerns destruction.
3368 If the answer is "yes", much of the design of the class follows (see [the rule of five](#Rc-five).
3370 ### <a name="Rc-dtor"></a> C.30: Define a destructor if a class needs an explicit action at object destruction
3374 A destructor is implicitly invoked at the end of an object's lifetime.
3375 If the default destructor is sufficient, use it.
3376 Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.
3380 template<typename A>
3381 struct final_action { // slightly simplified
3383 final_action(F a) :act{a} {}
3384 ~final_action() { act(); }
3387 template<typename A>
3388 final_action<A> finally(A act) // deduce action type
3390 return final_action<A>{a};
3395 auto act = finally([]{ cout << "Exit test\n"; }); // establish exit action
3397 if (something) return; // act done here
3401 The whole purpose of `final_action` is to get a piece of code (usually a lambda) executed upon destruction.
3405 There are two general categories of classes that need a user-defined destructor:
3407 * A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class.
3408 * A class that exists primarily to execute an action upon destruction, such as a tracer or `final_action`.
3412 class Foo { // bad; use the default destructor
3415 ~Foo() { s = ""; i = 0; vi.clear(); } // clean up
3422 The default destructor does it better, more efficiently, and can't get it wrong.
3426 If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`.
3430 Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.
3432 ### <a name="Rc-dtor-release"></a> C.31: All resources acquired by a class must be released by the class's destructor
3436 Prevention of resource leaks, especially in error cases.
3440 For resources represented as classes with a complete set of default operations, this happens automatically.
3445 ifstream f; // may own a file
3446 // ... no default operations defined or =deleted ...
3449 `X`'s `ifstream` implicitly closes any file it may have open upon destruction of its `X`.
3454 FILE* f; // may own a file
3455 // ... no default operations defined or =deleted ...
3458 `X2` may leak a file handle.
3462 What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail).
3463 If it does nevertheless, we have a problem that has no really good solution.
3464 For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
3465 See [discussion](#Sd-never-fail).
3466 To make the problem worse, many "close/release" operations are not retryable.
3467 Many have tried to solve this problem, but no general solution is known.
3468 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
3472 A class can hold pointers and references to objects that it does not own.
3473 Obviously, such objects should not be `delete`d by the class's destructor.
3476 Preprocessor pp { /* ... */ };
3477 Parser p { pp, /* ... */ };
3478 Type_checker tc { p, /* ... */ };
3480 Here `p` refers to `pp` but does not own it.
3484 * (Simple) If a class has pointer or reference member variables that are owners
3485 (e.g., deemed owners by using `gsl::owner`), then they should be referenced in its destructor.
3486 * (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership
3487 (e.g., look into the constructors).
3489 ### <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
3493 There is a lot of code that is non-specific about ownership.
3501 If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`.
3502 This will aide documentation and analysis.
3506 Look at the initialization of raw member pointers and member references and see if an allocation is used.
3508 ### <a name="Rc-dtor-ptr2"></a> C.33: If a class has an owning pointer member, define a destructor
3512 An owned object must be `deleted` upon destruction of the object that owns it.
3516 A pointer member may represent a resource.
3517 [A `T*` should not do so](#Rr-ptr), but in older code, that's common.
3518 Consider a `T*` a possible owner and therefore suspect.
3520 template<typename T>
3522 T* p; // BAD: vague about ownership of *p
3525 // ... no user-defined default operations ...
3528 void use(Smart_ptr<int> p1)
3530 auto p2 = p1; // error: p2.p leaked (if not nullptr and not owned by some other code)
3533 Note that if you define a destructor, you must define or delete [all default operations](#Rc-five):
3535 template<typename T>
3537 T* p; // BAD: vague about ownership of *p
3540 // ... no user-defined copy operations ...
3541 ~Smart_ptr2() { delete p; } // p is an owner!
3544 void use(Smart_ptr<int> p1)
3546 auto p2 = p1; // error: double deletion
3549 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:
3551 template<typename T>
3553 owner<T>* p; // OK: explicit about ownership of *p
3557 // ... copy and move operations ...
3558 ~Smart_ptr3() { delete p; }
3561 void use(Smart_ptr3<int> p1)
3563 auto p2 = p1; // error: double deletion
3568 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.
3572 Why not just require all owning pointers to be "smart pointers"?
3573 That would sometimes require non-trivial code changes and may affect ABIs.
3577 * A class with a pointer data member is suspect.
3578 * A class with an `owner<T>` should define its default operations.
3580 ### <a name="Rc-dtor-ref"></a> C.34: If a class has an owning reference member, define a destructor
3584 A reference member may represent a resource.
3585 It should not do so, but in older code, that's common.
3586 See [pointer members and destructors](#Rc-dtor-ptr).
3587 Also, copying may lead to slicing.
3591 class Handle { // Very suspect
3592 Shape& s; // use reference rather than pointer to prevent rebinding
3593 // BAD: vague about ownership of *p
3596 Handle(Shape& ss) : s{ss} { /* ... */ }
3600 The problem of whether `Handle` is responsible for the destruction of its `Shape` is the same as for [the pointer case](#Rc-dtor-ptr):
3601 If the `Handle` owns the object referred to by `s` it must have a destructor.
3605 class Handle { // OK
3606 owner<Shape&> s; // use reference rather than pointer to prevent rebinding
3609 Handle(Shape& ss) : s{ss} { /* ... */ }
3610 ~Handle() { delete &s; }
3614 Independently of whether `Handle` owns its `Shape`, we must consider the default copy operations suspect:
3616 Handle x {*new Circle{p1, 17}}; // the Handle had better own the Circle or we have a leak
3617 Handle y {*new Triangle{p1, p2, p3}};
3618 x = y; // the default assignment will try *x.s = *y.s
3620 That `x=y` is highly suspect.
3621 Assigning a `Triangle` to a `Circle`?
3622 Unless `Shape` has its [copy assignment `=deleted`](#Rc-copy-virtual), only the `Shape` part of `Triangle` is copied into the `Circle`.
3626 Why not just require all owning references to be replaced by "smart pointers"?
3627 Changing from references to smart pointers implies code changes.
3628 We don't (yet) have smart references.
3629 Also, that may affect ABIs.
3633 * A class with a reference data member is suspect.
3634 * A class with an `owner<T>` reference should define its default operations.
3636 ### <a name="Rc-dtor-virtual"></a> C.35: A base class with a virtual function needs a virtual destructor
3640 To prevent undefined behavior.
3641 If an application attempts to delete a derived class object through a base class pointer, the result is undefined if the base class's destructor is non-virtual.
3642 In general, the writer of a base class does not know the appropriate action to be done upon destruction.
3646 struct Base { // BAD: no virtual destructor
3651 string s {"a resource needing cleanup"};
3652 ~D() { /* ... do some cleanup ... */ }
3658 unique_ptr<Base> p = make_unique<D>();
3660 } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
3664 A virtual function defines an interface to derived classes that can be used without looking at the derived classes.
3665 Someone using such an interface is likely to also destroy using that interface.
3669 A destructor must be `public` or it will prevent stack allocation and normal heap allocation via smart pointer (or in legacy code explicit `delete`):
3672 ~X(); // private destructor
3678 X a; // error: cannot destroy
3679 auto p = make_unique<X>(); // error: cannot destroy
3684 (Simple) A class with any virtual functions should have a virtual destructor.
3686 ### <a name="Rc-dtor-fail"></a> C.36: A destructor may not fail
3690 In general we do not know how to write error-free code if a destructor should fail.
3691 The standard library requires that all classes it deals with have destructors that do not exit by throwing.
3704 if (cannot_release_a_resource) terminate();
3710 Many have tried to devise a fool-proof scheme for dealing with failure in destructors.
3711 None have succeeded to come up with a general scheme.
3712 This can be be a real practical problem: For example, what about a sockets that won't close?
3713 The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
3714 See [discussion](#Sd-dtor).
3715 To make the problem worse, many "close/release" operations are not retryable.
3716 If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
3720 Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program.
3724 If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow
3725 (maybe even by modifying some global state and hope something will notice and be able to take care of the problem).
3726 Be fully aware that this technique is special-purpose and error-prone.
3727 Consider the "my connection will not close" example.
3728 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.
3729 The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.
3733 If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully
3734 (e.g., by using a different clean-up mechanism from the one that threw an exception).
3738 (Simple) A destructor should be declared `noexcept`.
3740 ### <a name="Rc-dtor-noexcept"></a> C.37: Make destructors `noexcept`
3744 [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.
3748 (Simple) A destructor should be declared `noexcept`.
3750 ## <a name="SS-ctor"></a> C.ctor: Constructors
3752 A constructor defined how an object is initialized (constructed).
3754 ### <a name="Rc-ctor"></a> C.40: Define a constructor if a class has an invariant
3758 That's what constructors are for.
3762 class Date { // a Date represents a valid date
3763 // in the January 1, 1900 to December 31, 2100 range
3764 Date(int dd, int mm, int yy)
3765 :d{dd}, m{mm}, y{yy}
3767 if (!is_valid(d, m, y)) throw Bad_date{}; // enforce invariant
3774 It is often a good idea to express the invariant as an `Ensure` on the constructor.
3778 A constructor can be used for convenience even if a class does not have an invariant. For example:
3783 Rec(const string& ss) : s{ss} {}
3784 Rec(int ii) :i{ii} {}
3792 The C++11 initializer list rules eliminates the need for many constructors. For example:
3797 Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {} // redundant
3803 The `Rec2` constructor is redundant.
3804 Also, the default for `int` would be better done as a [member initializer](#Rc-in-class-initializer).
3806 **See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw).
3810 * Flag classes with user-define copy operations but no destructor (a user-defined copy is a good indicator that the class has an invariant)
3812 ### <a name="Rc-complete"></a> C.41: A constructor should create a fully initialized object
3816 A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
3821 FILE* f; // call init() before any other function
3825 void init(); // initialize f
3826 void read(); // read from f
3833 file.read(); // crash or bad read!
3835 file.init(); // too late
3839 Compilers do not read comments.
3841 **Exception**: If a valid object cannot conveniently be constructed by a constructor [use a factory function](#Rc-factory).
3845 If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release).
3846 The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisitions Is Initialization").
3848 ### <a name="Rc-throw"></a> C.42: If a constructor cannot construct a valid object, throw an exception
3852 Leaving behind an invalid object is asking for trouble.
3857 FILE* f; // call init() before any other function
3860 X2(const string& name)
3861 :f{fopen(name.c_str(), "r")}
3863 if (f == nullptr) throw runtime_error{"could not open" + name};
3867 void read(); // read from f
3873 X2 file {"Zeno"}; // throws if file isn't open
3874 file.read(); // fine
3880 class X3 { // bad: the constructor leaves a non-valid object behind
3881 FILE* f; // call init() before any other function
3885 X3(const string& name)
3886 :f{fopen(name.c_str(), "r")}, valid{false}
3888 if (f) valid = true;
3892 void is_valid() { return valid; }
3893 void read(); // read from f
3899 X3 file {"Heraclides"};
3900 file.read(); // crash or bad read!
3907 // ... handle error ...
3914 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. Leaving behind an invalid object an relying on users to consistently check an `is_valid()` function before use is tedious, error-prone, and inefficient.
3916 **Exception**: 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. There the `is_valid()` technique must be used. In such cases, check `is_valid()` consistently and immediately to simulate [RAII](#Rr-raii).
3918 **Alternative**: If you feel tempted to use some "post-constructor initialization" or "two-stage initialization" idiom, try not to do that. If you really have to, look at [factory functions](#Rc-factory).
3922 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
3923 * (Unknown) If a constructor has an `Ensures` contract, try to see if it holds as a postcondition.
3925 ### <a name="Rc-default0"></a> C.43: Give a class a default constructor
3929 Many language and library facilities rely on default constructors, e.g. `T a[10]` and `std::vector<T> v(10)` default initializes their elements.
3939 vector<Date> vd1(1000); // default Date needed here
3940 vector<Date> vd2(1000, Date{Month::october, 7, 1885}); // alternative
3942 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.
3943 `{0, 0, 0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's NaN.
3944 However, most realistic `Date` classes has a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.
3948 * Flag classes without a default constructor
3950 ### <a name="Rc-default00"></a> C.44: Prefer default constructors to be simple and non-throwing
3954 Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
3956 ##### Example, problematic
3958 template<typename T>
3959 class Vector0 { // elem points to space-elem element allocated using new
3961 Vector0() :Vector0{0} {}
3962 Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
3970 This is nice and general, but setting a `Vector0` to empty after an error involves an allocation, which may fail.
3971 Also, having a default `Vector` represented as `{new T[0], 0, 0}` seems wasteful.
3972 For example, `Vector0 v(100)` costs 100 allocations.
3976 template<typename T>
3977 class Vector1 { // elem is nullptr or elem points to space-elem element allocated using new
3979 Vector1() noexcept {} // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
3980 Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
3983 own<T*> elem = nullptr;
3988 Using `{nullptr, nullptr, nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks.
3989 Setting a `Vector1` to empty after detecting an error is trivial.
3993 * Flag throwing default constructors
3995 ### <a name="Rc-default"></a> C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
3999 Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
4003 class X1 { // BAD: doesn't use member initializers
4007 X1() :s{"default"}, i{1} { }
4014 string s = "default";
4017 // use compiler-generated default constructor
4023 (Simple) A default constructor should do more than just initialize member variables with constants.
4025 ### <a name="Rc-explicit"></a> C.46: By default, declare single-argument constructors explicit
4029 To avoid unintended conversions.
4040 String s = 10; // surprise: string of size 10
4044 If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`:
4049 Complex(double d); // OK: we want a conversion from d to {d, 0}
4053 Complex z = 10.7; // unsurprising conversion
4055 **See also**: [Discussion of implicit conversions](#Ro-conversion).
4059 (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".
4061 ### <a name="Rc-order"></a> C.47: Define and initialize member variables in the order of member declaration
4065 To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
4073 Foo(int x) :m2{x}, m1{++x} { } // BAD: misleading initializer order
4077 Foo x(1); // surprise: x.m1 == x.m2 == 2
4081 (Simple) A member initializer list should mention the members in the same order they are declared.
4083 **See also**: [Discussion](#Sd-order)
4085 ### <a name="Rc-in-class-initializer"></a> C.48: Prefer in-class initializers to member initializers in constructors for constant initializers
4089 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.
4098 X() :i{666}, s{"qqq"} { } // j is uninitialized
4099 X(int ii) :i{ii} {} // s is "" and j is uninitialized
4103 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.
4112 X2() = default; // all members are initialized to their defaults
4113 X2(int ii) :i{ii} {} // s and j initialized to their defaults
4117 **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:
4119 class X3 { // BAD: inexplicit, argument passing overhead
4124 X3(int ii = 666, const string& ss = "qqq", int jj = 0)
4125 :i{ii}, s{ss}, j{jj} { } // all members are initialized to their defaults
4131 * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
4132 * (Simple) Default arguments to constructors suggest an in-class initializer may be more appropriate.
4134 ### <a name="Rc-initialize"></a> C.49: Prefer initialization to assignment in constructors
4138 An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
4145 A() : s1{"Hello, "} { } // GOOD: directly construct
4154 B() { s1 = "Hello, "; } // BAD: default constructor followed by assignment
4158 class C { // UGLY, aka very bad
4161 C() { cout << *p; p = new int{10}; } // accidental use before initialized
4165 ### <a name="Rc-factory"></a> C.50: Use a factory function if you need "virtual behavior" during initialization
4169 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.
4178 f(); // BAD: virtual call in constructor
4182 virtual void f() = 0;
4191 B() { /* ... */ } // create an imperfectly initialized object
4193 virtual void PostInitialize() // to be called right after construction
4196 f(); // GOOD: virtual dispatch is safe
4201 virtual void f() = 0;
4204 static shared_ptr<T> Create() // interface for creating objects
4206 auto p = make_shared<T>();
4207 p->PostInitialize();
4212 class D : public B { /* "¦ */ }; // some derived class
4214 shared_ptr<D> p = D::Create<D>(); // creating a D object
4216 By making the constructor `protected` we avoid an incompletely constructed object escaping into the wild.
4217 By providing the factory function `Create()`, we make construction (on the free store) convenient.
4221 Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.
4223 **See also**: [Discussion](#Sd-factory)
4225 ### <a name="Rc-delegating"></a> C.51: Use delegating constructors to represent common actions for all constructors of a class
4229 To avoid repetition and accidental differences.
4233 class Date { // BAD: repetitive
4238 Date(int ii, Month mm, year yy)
4240 { if (!valid(i, m, y)) throw Bad_date{}; }
4242 Date(int ii, Month mm)
4243 :i{ii}, m{mm} y{current_year()}
4244 { if (!valid(i, m, y)) throw Bad_date{}; }
4248 The common action gets tedious to write and may accidentally not be common.
4257 Date2(int ii, Month mm, year yy)
4259 { if (!valid(i, m, y)) throw Bad_date{}; }
4261 Date2(int ii, Month mm)
4262 :Date2{ii, mm, current_year()} {}
4266 **See also**: If the "repeated action" is a simple initialization, consider [an in-class member initializer](#Rc-in-class-initializer).
4270 (Moderate) Look for similar constructor bodies.
4272 ### <a name="Rc-inheriting"></a> C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization
4276 If you need those constructors for a derived class, re-implementeing them is tedious and error prone.
4280 `std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them:
4283 // ... data and lots of nice constructors ...
4286 class Oper : public Rec {
4288 // ... no data members ...
4289 // ... lots of nice utility functions ...
4294 struct Rec2 : public Rec {
4300 int val = r.x; // uninitialized
4304 Make sure that every member of the derived class is initialized.
4306 ## <a name="SS-copy"></a> C.copy: Copy and move
4308 Value types should generally be copyable, but interfaces in a class hierarchy should not.
4309 Resource handles may or may not be copyable.
4310 Types can be defined to move for logical as well as performance reasons.
4312 ### <a name="Rc-copy-assignment"></a> C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`
4316 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)).
4322 Foo& operator=(const Foo& x)
4324 auto tmp = x; // GOOD: no need to check for self-assignment (other than performance)
4325 std::swap(*this, tmp);
4335 a = b; // assign lvalue: copy
4336 a = f(); // assign rvalue: potentially move
4340 The `swap` implementation technique offers the [strong guarantee](???).
4344 But what if you can get significant 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:
4346 template<typename T>
4349 Vector& operator=(const Vector&);
4358 Vector& Vector::operator=(const Vector& a)
4361 // ... use the swap technique, it can't be bettered ...
4364 // ... copy sz elements from *a.elem to elem ...
4366 // ... destroy the surplus elements in *this* and adjust size ...
4371 By writing directly to the target elements, we will get only [the basic guarantee](#???) rather than the strong guaranteed offered by the `swap` technique. Beware of [self assignment](#Rc-copy-self).
4373 **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&)`.
4374 See [copy constructor vs. `clone()`](#Rc-copy-virtual).
4378 * (Simple) An assignment operator should not be virtual. Here be dragons!
4379 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
4380 * (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators.
4381 Look at the destructor to determine if the type has pointer semantics or value semantics.
4383 ### <a name="Rc-copy-semantic"></a> C.61: A copy operation should copy
4387 That is the generally assumed semantics. After `x=y`, we should have `x == y`.
4388 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).
4392 class X { // OK: value semantics
4395 X(const X&); // copy X
4396 void modify(); // change the value of X
4398 ~X() { delete[] p; }
4404 bool operator==(const X& a, const X& b)
4406 return sz == a.sz && equal(p, p + sz, a.p, a.p + sz);
4412 copy(a.p, a.p + sz, a.p);
4417 if (x != y) throw Bad{};
4419 if (x == y) throw Bad{}; // assume value semantics
4423 class X2 { // OK: pointer semantics
4426 X2(const X&) = default; // shallow copy
4428 void modify(); // change the value of X
4435 bool operator==(const X2& a, const X2& b)
4437 return sz == a.sz && p == a.p;
4442 if (x != y) throw Bad{};
4444 if (x != y) throw Bad{}; // assume pointer semantics
4448 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.
4454 ### <a name="Rc-copy-self"></a> C.62: Make copy assignment safe for self-assignment
4458 If `x=x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks).
4462 The standard-library containers handle self-assignment elegantly and efficiently:
4464 std::vector<int> v = {3, 1, 4, 1, 5, 9};
4466 // the value of v is still {3, 1, 4, 1, 5, 9}
4470 The default assignment generated from members that handle self-assignment correctly handles self-assignment.
4473 vector<pair<int, int>> v;
4480 b = b; // correct and efficient
4484 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)).
4490 Foo& operator=(const Foo& a);
4494 Foo& Foo::operator=(const Foo& a) // OK, but there is a cost
4496 if (this == &a) return *this;
4502 This is obviously safe and apparently efficient.
4503 However, what if we do one self-assignment per million assignments?
4504 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).
4507 Foo& Foo::operator=(const Foo& a) // simpler, and probably much better
4514 `std::string` is safe for self-assignment and so are `int`. All the cost is carried by the (rare) case of self-assignment.
4518 (Simple) Assignment operators should not contain the pattern `if (this == &a) return *this;` ???
4520 ### <a name="Rc-move-assignment"></a> C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const &`
4524 It is simple and efficient.
4526 **See**: [The rule for copy-assignment](#Rc-copy-assignment).
4530 Equivalent to what is done for [copy-assignment](#Rc-copy-assignment).
4532 * (Simple) An assignment operator should not be virtual. Here be dragons!
4533 * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers.
4534 * (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.
4536 ### <a name="Rc-move-semantic"></a> C.64: A move operation should move and leave its source in valid state
4540 That is the generally assumed semantics. After `x=std::move(y)` the value of `x` should be the value `y` had and `y` should be in a valid state.
4544 template<typename T>
4545 class X { // OK: value semantics
4549 void modify(); // change the value of X
4551 ~X() { delete[] p; }
4559 :p{a.p}, sz{a.sz} // steal representation
4561 a.p = nullptr; // set to "empty"
4571 } // OK: x can be destroyed
4575 Ideally, that moved-from should be the default value of the type. Ensure that unless there is an exceptionally good reason not to. However, not all types have a default value and for some types establishing the default value can be expensive. The standard requires only that the moved-from object can be destroyed.
4576 Often, we can easily and cheaply do better: The standard library assumes that it it possible to assign to a moved-from object. Always leave the moved-from object in some (necessarily specified) valid state.
4580 Unless there is an exceptionally strong reason not to, make `x = std::move(y); y = z;` work with the conventional semantics.
4584 (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.
4586 ### <a name="Rc-move-self"></a> C.65: Make move assignment safe for self-assignment
4590 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.
4598 Foo& operator=(Foo&& a);
4602 Foo& Foo::operator=(Foo&& a) // OK, but there is a cost
4604 if (this == &a) return *this; // this line is redundant
4610 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.
4614 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).
4618 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.
4622 Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment):
4624 // move from other.oter to this->ptr
4625 T* temp = other.ptr;
4626 other.ptr = nullptr;
4632 * (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.
4633 * (Not enforceable) Look at the use of standard-library container types (incl. `string`) and consider them safe for ordinary (not life-critical) uses.
4635 ### <a name="Rc-move-noexcept"></a> C.66: Make move operations `noexcept`
4639 A throwing move violates most people's reasonably assumptions.
4640 A non-throwing move will be used more efficiently by standard-library and language facilities.
4644 template<typename T>
4647 Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.sz = 0; a.elem = nullptr; }
4648 Vector& operator=(Vector&& a) noexcept { elem = a.elem; sz = a.sz; a.sz = 0; a.elem = nullptr; }
4655 These copy operations do not throw.
4659 template<typename T>
4662 Vector2(Vector2&& a) { *this = a; } // just use the copy
4663 Vector2& operator=(Vector2&& a) { *this = a; } // just use the copy
4670 This `Vector2` is not just inefficient, but since a vector copy requires allocation, it can throw.
4674 (Simple) A move operation should be marked `noexcept`.
4676 ### <a name="Rc-copy-virtual"></a> C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired
4680 To prevent slicing, because the normal copy operations will copy only the base portion of a derived object.
4684 class B { // BAD: base class doesn't suppress copying
4686 // ... nothing about copy operations, so uses default ...
4689 class D : public B {
4690 string moredata; // add a data member
4694 auto d = make_unique<D>();
4695 auto b = make_unique<B>(d); // oops, slices the object; gets only d.data but drops d.moredata
4699 class B { // GOOD: base class suppresses copying
4700 B(const B&) =delete;
4701 B& operator=(const B&) =delete;
4702 virtual unique_ptr<B> clone() { return /* B object */; }
4706 class D : public B {
4707 string moredata; // add a data member
4708 unique_ptr<B> clone() override { return /* D object */; }
4712 auto d = make_unique<D>();
4713 auto b = d.clone(); // ok, deep clone
4717 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.
4721 A class with any virtual function should not have a copy constructor or copy assignment operator (compiler-generated or handwritten).
4723 ## C.other: Other default operations
4727 ### <a name="Rc-=default"></a> C.80: Use `=default` if you have to be explicit about using the default semantics
4731 The compiler is more likely to get the default semantics right and you cannot implement these function better than the compiler.
4738 Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
4739 ~Tracer() { cerr << "exiting " << message << '\n'; }
4741 Tracer(const Tracer&) = default;
4742 Tracer& operator=(const Tracer&) = default;
4743 Tracer(Tracer&&) = default;
4744 Tracer& operator=(Tracer&&) = default;
4747 Because we defined the destructor, we must define the copy and move operations. The `=default` is the best and simplest way of doing that.
4754 Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
4755 ~Tracer2() { cerr << "exiting " << message << '\n'; }
4757 Tracer2(const Tracer2& a) : message{a.message} {}
4758 Tracer2& operator=(const Tracer2& a) { message = a.message; }
4759 Tracer2(Tracer2&& a) :message{a.message} {}
4760 Tracer2& operator=(Tracer2&& a) { message = a.message; }
4763 Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.
4767 (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
4769 ### <a name="Rc-=delete"></a> C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)
4773 In a few cases, a default operation is not desirable.
4779 ~Immortal() = delete; // do not allow destruction
4785 Immortal ugh; // error: ugh cannot be destroyed
4786 Immortal* p = new Immortal{};
4787 delete p; // error: cannot destroy *p
4792 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:
4794 template <class T, class D = default_delete<T>> class unique_ptr {
4797 constexpr unique_ptr() noexcept;
4798 explicit unique_ptr(pointer p) noexcept;
4800 unique_ptr(unique_ptr&& u) noexcept; // move constructor
4802 unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
4806 unique_ptr<int> make(); // make "something" and return it by moving
4810 unique_ptr<int> pi {};
4811 auto pi2 {pi}; // error: no move constructor from lvalue
4812 auto pi3 {make()}; // OK, move: the result of make() is an rvalue
4817 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.
4819 ### <a name="Rc-ctor-virtual"></a> C.82: Don't call virtual functions in constructors and destructors
4823 The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class.
4824 This can be most confusing.
4825 Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.
4831 virtual void f() = 0; // not implemented
4832 virtual void g(); // implemented with base version
4833 virtual void h(); // implemented with base version
4836 class derived : public base {
4838 void g() override; // provide derived implementation
4839 void h() final; // provide derived implementation
4843 f(); // BAD: attempt to call an unimplemented virtual function
4845 g(); // BAD: will call derived::g, not dispatch further virtually
4846 derived::g(); // GOOD: explicitly state intent to call only the visible version
4848 h(); // ok, no qualification needed, h is final
4852 Note that calling a specific explicitly qualified function is not a virtual call even if the function is `virtual`.
4854 **See also** [factory functions](#Rc-factory) for how to achieve the effect of a call to a derived class function without risking undefined behavior.
4856 ### <a name="Rc-swap"></a> C.83: For value-like types, consider providing a `noexcept` swap function
4860 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).
4867 void swap(Foo& rhs) noexcept
4870 std::swap(m2, rhs.m2);
4877 Providing a nonmember `swap` function in the same namespace as your type for callers' convenience.
4879 void swap(Foo& a, Foo& b)
4886 * (Simple) A class without virtual functions should have a `swap` member function declared.
4887 * (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
4889 ### <a name="Rc-swap-fail"></a> C.84: A `swap` function may not fail
4893 `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 The standard-library containers and algorithms will not work correctly if a swap of an element type fails.
4897 void swap(My_vector& x, My_vector& y)
4899 auto tmp = x; // copy elements
4904 This is not just slow, but if a memory allocation occur for the elements in `tmp`, this `swap` may throw and would make STL algorithms fail is used with them.
4908 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
4910 ### <a name="Rc-swap-noexcept"></a> C.85: Make `swap` `noexcept`
4914 [A `swap` may not fail](#Rc-swap-fail).
4915 If a `swap` tries to exit with an exception, it's a bad design error and the program had better terminate.
4919 (Simple) When a class has a `swap` member function, it should be declared `noexcept`.
4921 ### <a name="Rc-eq"></a> C.86: Make `==` symmetric with respect to operand types and `noexcept`
4925 Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.
4926 `==` is a fundamental operations and programmers should be able to use it without fear of failure.
4935 bool operator==(const X& a, const X& b) noexcept { return a.name == b.name && a.number == b.number; }
4942 bool operator==(const B& a) const { return name == a.name && number == a.number; }
4946 `B`'s comparison accepts conversions for its second operand, but not its first.
4950 If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw.
4951 The alternative is to make two failure states compare equal and any valid state compare false against the failure state.
4957 ### <a name="Rc-eq-base"></a> C.87: Beware of `==` on base classes
4961 It is really hard to write a foolproof and useful `==` for a hierarchy.
4968 virtual bool operator==(const B& a) const
4970 return name == a.name && number == a.number;
4975 // `B`'s comparison accepts conversions for its second operand, but not its first.
4979 virtual bool operator==(const D& a) const
4981 return name == a.name && number == a.number && character == a.character;
4988 b == d; // compares name and number, ignores d's character
4989 d == b; // error: no == defined
4991 d == d2; // compares name, number, and character
4993 b2 == d; // compares name and number, ignores d2's and d's character
4995 Of course there are way of making `==` work in a hierarchy, but the naive approaches do not scale
5001 ### <a name="Rc-lt"></a> C.88: Make `<` symmetric with respect to operand types and `noexcept`
5015 ### <a name="Rc-hash"></a> C.89: Make a `hash` `noexcept`
5029 ## <a name="SS-containers"></a> C.con: Containers and other resource handles
5031 A container is an object holding a sequence of objects of some type; `std::vector` is the archetypical container.
5032 A resource handle is a class that owns a resource; `std::vector` is the typical resource handle; its resource is its sequence of elements.
5034 Summary of container rules:
5036 * [C.100: Follow the STL when defining a container](#Rcon-stl)
5037 * [C.101: Give a container value semantics](#Rcon-val)
5038 * [C.102: Give a container move operations](#Rcon-move)
5039 * [C.103: Give a container an initializer list constructor](#Rcon-init)
5040 * [C.104: Give a container a default constructor that sets it to empty](#Rcon-empty)
5041 * [C.105: Give a constructor and `Extent` constructor](#Rcon-val)
5043 * [C.109: If a resource handle has pointer semantics, provide `*` and `->`](#rcon-ptr)
5045 **See also**: [Resources](#S-resource)
5047 ## <a name="SS-lambdas"></a> C.lambdas: Function objects and lambdas
5049 A function object is an object supplying an overloaded `()` so that you can call it.
5050 A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object.
5054 * [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)
5055 * [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
5056 * [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)
5057 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
5059 ## <a name="SS-hier"></a> C.hier: Class hierarchies (OOP)
5061 A class hierarchy is constructed to represent a set of hierarchically organized concepts (only).
5062 Typically base classes act as interfaces.
5063 There are two major uses for hierarchies, often named implementation inheritance and interface inheritance.
5065 Class hierarchy rule summary:
5067 * [C.120: Use class hierarchies to represent concepts with inherent hierarchical structure](#Rh-domain)
5068 * [C.121: If a base class is used as an interface, make it a pure abstract class](#Rh-abstract)
5069 * [C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed](#Rh-separation)
5071 Designing rules for classes in a hierarchy summary:
5073 * [C.126: An abstract class typically doesn't need a constructor](#Rh-abstract-ctor)
5074 * [C.127: A class with a virtual function should have a virtual destructor](#Rh-dtor)
5075 * [C.128: Use `override` to make overriding explicit in large class hierarchies](#Rh-override)
5076 * [C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance](#Rh-kind)
5077 * [C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead](#Rh-copy)
5079 * [C.131: Avoid trivial getters and setters](#Rh-get)
5080 * [C.132: Don't make a function `virtual` without reason](#Rh-virtual)
5081 * [C.133: Avoid `protected` data](#Rh-protected)
5082 * [C.134: Ensure all data members have the same access level](#Rh-public)
5083 * [C.135: Use multiple inheritance to represent multiple distinct interfaces](#Rh-mi-interface)
5084 * [C.136: Use multiple inheritance to represent the union of implementation attributes](#Rh-mi-implementation)
5085 * [C.137: Use `virtual` bases to avoid overly general base classes](#Rh-vbase)
5086 * [C.138: Create an overload set for a derived class and its bases with `using`](#Rh-using)
5088 Accessing objects in a hierarchy rule summary:
5090 * [C.145: Access polymorphic objects through pointers and references](#Rh-poly)
5091 * [C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable](#Rh-dynamic_cast)
5092 * [C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error](#Rh-ptr-cast)
5093 * [C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative](#Rh-ref-cast)
5094 * [C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`](#Rh-smart)
5095 * [C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s or another smart pointer](#Rh-make_unique)
5096 * [C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s](#Rh-make_shared)
5097 * [C.152: Never assign a pointer to an array of derived class objects to a pointer to its base](#Rh-array)
5099 ### <a name="Rh-domain"></a> C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)
5103 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.
5105 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.
5109 ??? Good old Shape example?
5113 Do *not* represent non-hierarchical domain concepts as class hierarchies.
5115 template<typename T>
5119 virtual T& get() = 0;
5120 virtual void put(T&) = 0;
5121 virtual void insert(Position) = 0;
5123 // vector operations:
5124 virtual T& operator[](int) = 0;
5125 virtual void sort() = 0;
5128 virtual void balance() = 0;
5132 Here most overriding classes cannot implement most of the functions required in the interface well.
5133 Thus the base class becomes an implementation burden.
5134 Furthermore, the user of `Container` cannot rely on the member functions actually performing a meaningful operations reasonably efficiently;
5135 it may throw an exception instead.
5136 Thus users have to resort to run-time checking and/or
5137 not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a `dynamic_cast`).
5141 * Look for classes with lots of members that do nothing but throw.
5142 * Flag every use of a nonpublic base class where the derived class does not override a virtual function or access a protected base member.
5144 ### <a name="Rh-abstract"></a> C.121: If a base class is used as an interface, make it a pure abstract class
5148 A class is more stable (less brittle) if it does not contain data. Interfaces should normally be composed entirely of public pure virtual functions.
5156 * Warn on any class that contains data members and also has an overridable (non-`final`) virtual function.
5158 ### <a name="Rh-separation"></a> C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed
5162 Such as on an ABI (link) boundary.
5172 ## C.hierclass: Designing classes in a hierarchy:
5174 ### <a name="Rh-abstract-ctor"></a> C.126: An abstract class typically doesn't need a constructor
5178 An abstract class typically does not have any data for a constructor to initialize.
5186 * A base class constructor that does work, such as registering an object somewhere, may need a constructor.
5187 * In extremely rare cases, you might find a reasonable for an abstract class to have a bit of data shared by all derived classes
5188 (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.
5192 Flag abstract classes with constructors.
5194 ### <a name="Rh-dtor"></a> C.127: A class with a virtual function should have a virtual destructor
5198 A class with a virtual function is usually (and in general) used via a pointer to base, including that the last user has to call delete on a pointer to base, often via a smart pointer to base.
5203 // ... no destructor ...
5206 struct D : B { // bad: class with a resource derived from a class without a virtual destructor
5207 string s {"default"};
5213 delete p; // leak the string
5218 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 and 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 functions to enforce the allocation with `make_shared`.
5222 * Flag a class with a virtual function and no virtual destructor. Note that this rule needs only be enforced for the first (base) class in which it occurs, derived classes inherit what they need. This flags the place where the problem arises, but can give false positives.
5223 * Flag `delete` of a class with a virtual function but no virtual destructor.
5225 ### <a name="Rh-override"></a> C.128: Use `override` to make overriding explicit in large class hierarchies
5229 Readability. Detection of mistakes. Explicit `override` allows the compiler to catch mismatch of types and/or names between base and derived classes.
5235 virtual void f2(int);
5236 virtual void f3(int);
5241 void f1(int); // warn: D::f1() hides B::f1()
5242 void f2(int); // warn: no explicit override
5243 void f3(double); // warn: D::f3() hides B::f3()
5249 * Compare names in base and derived classes and flag uses of the same name that does not override.
5250 * Flag overrides without `override`.
5252 ### <a name="Rh-kind"></a> C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance
5256 ??? Herb: I've become a non-fan of implementation inheritance -- seems most often an antipattern. Are there reasonable examples of it?
5266 ### <a name="Rh-copy"></a> C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead
5270 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 in derived classes return the derived type (use a covariant return type).
5276 virtual base* clone() = 0;
5279 class derived : public base {
5281 derived* clone() override;
5284 Note that because of language rules, the covariant return type cannot be a smart pointer.
5288 * Flag a class with a virtual function and a non-user-defined copy operation.
5289 * Flag an assignment of base class objects (objects of a class from which another has been derived).
5291 ### <a name="Rh-get"></a> C.131: Avoid trivial getters and setters
5295 A trivial getter or setter adds no semantic value; the data item could just as well be `public`.
5303 point(int xx, int yy) : x{xx}, y{yy} { }
5304 int get_x() { return x; }
5305 void set_x(int xx) { x = xx; }
5306 int get_y() { return y; }
5307 void set_y(int yy) { y = yy; }
5308 // no behavioral member functions
5311 Consider making such a class a `struct` -- that is, a behaviorless bunch of variables, all public data and no member functions.
5320 A getter or a setter that converts from an internal type to an interface type is not trivial (it provides a form of information hiding).
5324 Flag multiple `get` and `set` member functions that simply access a member without additional semantics.
5326 ### <a name="Rh-virtual"></a> C.132: Don't make a function `virtual` without reason
5330 Redundant `virtual` increases run-time and object-code size.
5331 A virtual function can be overridden and is thus open to mistakes in a derived class.
5332 A virtual function ensures code replication in a templated hierarchy.
5340 virtual int size() const { return sz; } // bad: what good could a derived class do?
5342 T* elem; // the elements
5343 int sz; // number of elements
5346 This kind of "vector" isn't meant to be used as a base class at all.
5350 * Flag a class with virtual functions but no derived classes.
5351 * Flag a class where all member functions are virtual and have implementations.
5353 ### <a name="Rh-protected"></a> C.133: Avoid `protected` data
5357 `protected` data is a source of complexity and errors.
5358 `protected` data complicated the statement of invariants.
5359 `protected` data inherently violates the guidance against putting data in base classes, which usually leads to having to deal virtual inheritance as well.
5367 Protected member function can be just fine.
5371 Flag classes with `protected` data.
5373 ### <a name="Rh-public"></a> C.134: Ensure all data members have the same access level
5377 If they don't, the type is confused about what it's trying to do. Only if the type is not really an abstraction, but just a convenience bundle to group individual variables with no larger behavior (a behaviorless bunch of variables), make all data members `public` and don't provide functions with behavior. Otherwise, the type is an abstraction, so make all its data members `private`. Don't mix `public` and `private` data.
5385 Flag any class that has data members with different access levels.
5387 ### <a name="Rh-mi-interface"></a> C.135: Use multiple inheritance to represent multiple distinct interfaces
5391 Not all classes will necessarily support all interfaces, and not all callers will necessarily want to deal with all operations. Especially to break apart monolithic interfaces into "aspects" of behavior supported by a given derived class.
5399 This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common
5400 and such interfaces are often not easily or naturally organized into a single-rooted hierarchy.
5404 Such interfaces are typically abstract classes.
5410 ### <a name="Rh-mi-implementation"></a> C.136: Use multiple inheritance to represent the union of implementation attributes
5414 ??? Herb: Here's the second mention of implementation inheritance. I'm very skeptical, even of single implementation inheritance, never mind multiple implementation inheritance which just seems frightening -- I don't think that even policy-based design really needs to inherit from the policy types. Am I missing some good examples, or could we consider discouraging this as an anti-pattern?
5422 This a relatively rare use because implementation can often be organized into a single-rooted hierarchy.
5426 ??? Herb: How about opposite enforcement: Flag any type that inherits from more than one non-empty base class?
5428 ### <a name="Rh-vbase"></a> C.137: Use `virtual` bases to avoid overly general base classes
5446 ### <a name="Rh-using"></a> C.138: Create an overload set for a derived class and its bases with `using`
5456 ## C.hier-access: Accessing objects in a hierarchy
5458 ### <a name="Rh-poly"></a> C.145: Access polymorphic objects through pointers and references
5462 If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
5466 struct B { int a; virtual int f(); };
5467 struct D : B { int b; int f() override; };
5482 Both `d`s are sliced.
5486 You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
5498 ### <a name="Rh-dynamic_cast"></a> C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable
5502 `dynamic_cast` is checked at run time.
5506 struct B { // an interface
5511 struct D : B { // a wider interface
5518 if (D* pd = dynamic_cast<D*>(pb)) {
5519 // ... use D's interface ...
5522 // .. make do with B's interface ...
5528 Like other casts, `dynamic_cast` is overused.
5529 [Prefer virtual functions to casting](#???).
5530 Prefer [static polymorphism](#???) to hierarchy navigation where it is possible (no run-time resolution necessary)
5531 and reasonably convenient.
5535 If your implementation provided a really slow `dynamic_cast`, you may have to use a workaround.
5536 However, all workarounds that cannot be statically resolved involve explicit casting (typically `static_cast`) and are error-prone.
5537 You will basically be crafting your own special-purpose `dynamic_cast`.
5538 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)
5539 and that your use of `dynamic_cast` is really performance critical.
5543 Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`.
5545 ### <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
5549 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.
5559 ### <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
5573 ### <a name="Rh-smart"></a> C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new`
5577 Avoid resource leaks.
5583 auto p = new int {7}; // bad: initialize local pointers with new
5584 auto q = make_unique<int>(9); // ok: guarantee the release of the memory allocated for 9
5585 if (0 < i) return; // maybe return and leak
5586 delete p; // too late
5591 * Flag initialization of a naked pointer with the result of a `new`
5592 * Flag `delete` of local variable
5594 ### <a name="Rh-make_unique"></a> C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s or other smart pointers
5598 `make_unique` gives a more concise statement of the construction.
5602 unique_ptr<Foo> p {new<Foo>{7}}; // OK: but repetitive
5604 auto q = make_unique<Foo>(7); // Better: no repetition of Foo
5608 * Flag the repetitive usage of template specialization list `<Foo>`
5609 * Flag variables declared to be `unique_ptr<Foo>`
5611 ### <a name="Rh-make_shared"></a> C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s
5615 `make_shared` gives a more concise statement of the construction.
5616 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.
5620 shared_ptr<Foo> p {new<Foo>{7}}; // OK: but repetitive; and separate allocations for the Foo and shared_ptr's use count
5622 auto q = make_shared<Foo>(7); // Better: no repetition of Foo; one object
5626 * Flag the repetitive usage of template specialization list`<Foo>`
5627 * Flag variables declared to be `shared_ptr<Foo>`
5629 ### <a name="Rh-array"></a> C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
5633 Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
5637 struct B { int x; };
5638 struct D : B { int y; };
5642 D a[] = { {1, 2}, {3, 4}, {5, 6} };
5643 B* p = a; // bad: a decays to &a[0] which is converted to a B*
5644 p[1].x = 7; // overwrite D[0].y
5646 use(a); // bad: a decays to &a[0] which is converted to a B*
5650 * Flag all combinations of array decay and base to derived conversions.
5651 * Pass an array as an `array_view` rather than as a pointer, and don't let the array name suffer a derived-to-base conversion before getting into the `array_view`
5653 # <a name="SS-overload"></a> C.over: Overloading and overloaded operators
5655 You can overload ordinary functions, template functions, and operators.
5656 You cannot overload function objects.
5658 Overload rule summary:
5660 * [C.160: Define operators primarily to mimic conventional usage](#Ro-conventional)
5661 * [C.161: Use nonmember functions for symmetric operators](#Ro-symmetric)
5662 * [C.162: Overload operations that are roughly equivalent](#Ro-equivalent)
5663 * [C.163: Overload only for operations that are roughly equivalent](#Ro-equivalent-2)
5664 * [C.164: Avoid conversion operators](#Ro-conversion)
5665 * [C.170: If you feel like overloading a lambda, use a generic lambda](#Ro-lambda)
5667 ### <a name="Ro-conventional"></a> C.160: Define operators primarily to mimic conventional usage
5675 X operator+(X a, X b) { return a.v - b.v; } // bad: makes + subtract
5677 ???. Non-member operators: namespace-level definition (traditional?) vs friend definition (as used by boost.operator, limits lookup to ADL only)
5681 Possibly impossible.
5683 ### <a name="Ro-symmetric"></a> C.161: Use nonmember functions for symmetric operators
5687 If you use member functions, you need two.
5688 Unless you use a non-member function for (say) `==`, `a == b` and `b == a` will be subtly different.
5692 bool operator==(Point a, Point b) { return a.x == b.x && a.y == b.y; }
5696 Flag member operator functions.
5698 ### <a name="Ro-equivalent"></a> C.162: Overload operations that are roughly equivalent
5702 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.
5709 void print(int a, int base);
5710 void print(const string&);
5712 These three functions all prints their arguments (appropriately). Conversely
5714 void print_int(int a);
5715 void print_based(int a, int base);
5716 void print_string(const string&);
5718 These three functions all prints their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code.
5724 ### <a name="Ro-equivalent-2"></a> C.163: Overload only for operations that are roughly equivalent
5728 Having the same name for logically different functions is confusing and leads to errors when using generic programming.
5734 void open_gate(Gate& g); // remove obstacle from garage exit lane
5735 void fopen(const char*name, const char* mode); // open file
5737 The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:
5739 void open(Gate& g); // remove obstacle from garage exit lane
5740 void open(const char*name, const char* mode ="r"); // open file
5742 The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion.
5743 Fortunately, the type system will catch many such mistakes.
5747 be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`.
5753 ### <a name="Ro-conversion"></a> C.164: Avoid conversion operators
5757 Implicit conversions can be essential (e.g., `double` to '`int`) but often cause surprises (e.g., `String` to C-style string).
5761 Prefer explicitly named conversions until a serious need is demonstrated.
5762 By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion)
5763 and frequently needed. Do not introduce implicit conversions (through conversion operators or non-`explicit` constructors)
5764 just to gain a minor convenience.
5768 class String { // handle ownership and access to a sequence of characters
5770 String(czstring p); // copy from *p to *(this->elem)
5772 operator zstring() { return elem; }
5776 void user(zstring p)
5779 String s {"Trouble ahead!"};
5786 The string allocated for `s` and assigned to `p` is destroyed before it can be used.
5790 Flag all conversion operators.
5792 ### <a name="Ro-lambda"></a> C.170: If you feel like overloading a lambda, use a generic lambda
5796 You can overload by defining two different lambdas with the same name.
5802 auto f = [](char); // error: cannot overload variable and function
5804 auto g = [](int) { /* ... */ };
5805 auto g = [](double) { /* ... */ }; // error: cannot overload variables
5807 auto h = [](auto) { /* ... */ }; // OK
5811 The compiler catches attempt to overload a lambda.
5813 ## <a name="SS-union"></a> C.union: Unions
5819 * [C.180: Use `union`s to ???](#Ru-union)
5820 * [C.181: Avoid "naked" `union`s](#Ru-naked)
5821 * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous)
5824 ### <a name="Ru-union"></a> C.180: Use `union`s to ???
5826 ??? When should unions be used, if at all? What's a good future-proof way to re-interpret object representations of PODs?
5841 ### <a name="Ru-naked"></a> C.181: Avoid "naked" `union`s
5845 Naked unions are a source of type errors.
5847 **Alternative**: Wrap them in a class together with a type field.
5849 **Alternative**: Use `variant`.
5859 ### <a name="Ru-anonymous"></a> C.182: Use anonymous `union`s to implement tagged unions
5873 # <a name="S-enum"></a> Enum: Enumerations
5875 Enumerations are used to define sets of integer values and for defining types for such sets of values. There are two kind of enumerations, "plain" `enum`s and `class enum`s.
5877 Enumeration rule summary:
5879 * [Enum.1: Prefer enums over macros](#Renum-macro)
5880 * [Enum.2: Use enumerations to represent sets of named constants](#Renum-set)
5881 * [Enum.3: Prefer class enums over ``plain'' enums](#Renum-class)
5882 * [Enum.4: Define operations on enumerations for safe and simple use](#Renum-oper)
5883 * [Enum.5: Don't use ALL_CAPS for enumerators](#Renum-caps)
5884 * [Enum.6: Use unnamed enumerations for ???](#Renum-unnamed)
5887 ### <a name="Renum-macro"></a> Enum.1: Prefer enums over macros
5891 Macros do not obey scope and type rules.
5901 ### <a name="Renum-set"></a> Enum.2: Use enumerations to represent sets of named constants
5915 ### <a name="Renum-class"></a> Enum.3: Prefer class enums over ``plain'' enums
5919 To minimize surprises.
5929 ### <a name="Renum-oper"></a> Enum.4: Define operations on enumerations for safe and simple use
5933 Convenience of use and avoidance of errors.
5943 ### <a name="Renum-caps"></a> Enum.5: Don't use ALL_CAPS for enumerators
5947 Avoid clashes with macros.
5957 ### <a name="Renum-unnamed"></a> Enum.6: Use unnamed enumerations for ???
5971 # <a name="S-resource"></a> R: Resource management
5973 This section contains rules related to resources.
5974 A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks.
5975 The reason it must be released is typically that it can be in short supply, so even delayed release may do harm.
5976 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.
5977 An entity that is responsible for releasing a resource is called an owner.
5979 There are a few cases where leaks can be acceptable or even optimal:
5980 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.
5981 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.
5982 Here, we ignore such cases.
5984 * Resource management rule summary:
5986 * [R.1: Manage resources automatically using resource handles and RAII (resource acquisition is initialization)](#Rr-raii)
5987 * [R.2: In interfaces, use raw pointers to denote individual objects (only)](#Rr-use-ptr)
5988 * [R.3: A raw pointer (a `T*`) is non-owning](#Rr-ptr)
5989 * [R.4: A raw reference (a `T&`) is non-owning](#Rr-ref)
5990 * [R.5: Prefer scoped objects](#Rr-scoped)
5991 * [R.6: Avoid non-`const` global variables](#Rr-global)
5993 * Allocation and deallocation rule summary:
5995 * [R.10: Avoid `malloc()` and `free()`](#Rr-mallocfree)
5996 * [R.11: Avoid calling `new` and `delete` explicitly](#Rr-newdelete)
5997 * [R.12: Immediately give the result of an explicit resource allocation to a manager object](#Rr-immediate-alloc)
5998 * [R.13: Perform at most one explicit resource allocation in a single expression statement](#Rr-single-alloc)
5999 * [R.14: ??? array vs. pointer parameter](#Rr-ap)
6000 * [R.15: Always overload matched allocation/deallocation pairs](#Rr-pair)
6002 * <a name="Rr-summary-smartptrs"></a> Smart pointer rule summary:
6004 * [R.20: Use `unique_ptr` or `shared_ptr` to represent ownership](#Rr-owner)
6005 * [R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership](#Rr-unique)
6006 * [R.22: Use `make_shared()` to make `shared_ptr`s](#Rr-make_shared)
6007 * [R.23: Use `make_unique()` to make `unique_ptr`s](#Rr-make_unique)
6008 * [R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s](#Rr-weak_ptr)
6009 * [R.30: Take smart pointers as parameters only to explicitly express lifetime semantics](#Rr-smartptrparam)
6010 * [R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`](#Rr-smart)
6011 * [R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`](#Rr-uniqueptrparam)
6012 * [R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the`widget`](#Rr-reseat)
6013 * [R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner](#Rr-sharedptrparam-owner)
6014 * [R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer](#Rr-sharedptrparam)
6015 * [R.36: Take a `const shared_ptr<widget>&` parameter to express that it might retain a reference count to the object ???](#Rr-sharedptrparam-const)
6016 * [R.37: Do not pass a pointer or reference obtained from an aliased smart pointer](#Rr-smartptrget)
6018 ### <a name="Rr-raii"></a> Rule R.1: Manage resources automatically using resource handles and RAII (resource acquisition is initialization)
6022 To avoid leaks and the complexity of manual resource management.
6023 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`.
6024 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.
6030 void send(X* x, cstring_view destination)
6032 auto port = OpenPort(destination);
6042 In this code, you have to remember to `unlock`, `ClosePort`, and `delete` on all paths, and do each exactly once.
6043 Further, if any of the code marked `...` throws an exception, then `x` is leaked and `my_mutex` remains locked.
6049 void send(unique_ptr<X> x, cstring_view destination) // x owns the X
6051 Port port{destination}; // port owns the PortHandle
6052 lock_guard<mutex> guard{my_mutex}; // guard owns the lock
6056 } // automatically unlocks my_mutex and deletes the pointer in x
6058 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.
6060 What is `Port`? A handy wrapper that encapsulates the resource:
6065 Port(cstring_view destination) : port{OpenPort(destination)} { }
6066 ~Port() { ClosePort(port); }
6067 operator PortHandle() { return port; }
6069 // port handles can't usually be cloned, so disable copying and assignment if necessary
6070 Port(const Port&) =delete;
6071 Port& operator=(const Port&) =delete;
6076 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)
6078 **See also**: [RAII](#Rr-raii).
6080 ### <a name="Rr-use-ptr"></a> R.2: In interfaces, use raw pointers to denote individual objects (only)
6084 Arrays are best represented by a container type (e.g., `vector` (owning)) or an `array_view` (non-owning).
6085 Such containers and views hold sufficient information to do range checking.
6089 void f(int* p, int n) // n is the number of elements in p[]
6092 p[2] = 7; // bad: subscript raw pointer
6096 The compiler does not read comments, and without reading other code you do not know whether `p` really points to `n` elements.
6097 Use an `array_view` instead.
6101 void g(int* p, int fmt) // print *p using format #fmt
6103 // ... uses *p and p[0] only ...
6106 **Exception**: C-style strings are passed as single pointers to a zero-terminated sequence of characters.
6107 Use `zstring` rather than `char*` to indicate that you rely on that convention.
6111 Many current uses of pointers to a single element could be references.
6112 However, where `nullptr` is a possible value, a reference may not be an reasonable alternative.
6116 * Flag pointer arithmetic (including `++`) on a pointer that is not part of a container, view, or iterator.
6117 This rule would generate a huge number of false positives if applied to an older code base.
6118 * Flag array names passed as simple pointers
6120 ### <a name="Rr-ptr"></a> R.3: A raw pointer (a `T*`) is non-owning
6124 There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning.
6125 We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
6131 int* p1 = new int{7}; // bad: raw owning pointer
6132 auto p2 = make_unique<int>(7); // OK: the int is owned by a unique pointer
6136 The `unique_ptr` protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The `T*` does not.
6140 template<typename T>
6144 T* p; // bad: it is unclear whether p is owning or not
6145 T* q; // bad: it is unclear whether q is owning or not
6148 We can fix that problem by making ownership explicit:
6150 template<typename T>
6154 owner<T> p; // OK: p is owning
6155 T* q; // OK: q is not owning
6160 The fact that there are billions of lines of code that violates this rule against owning `T*`s cannot be ignored.
6161 This code cannot all be rewritten (ever assuming good code transformation software).
6162 This problem cannot be solved (at scale) by transforming all owning pointer to `unique_ptr`s and `shared_ptr`s, partly because we need/use owning "raw pointers" in the implementation of our fundamental resource handles. For example, most `vector` implementations have one owning pointer and two non-owning pointers.
6163 Also, many ABIs (and essentially all interfaces to C code) use `T*`s, some of them owning.
6167 `owner<T>` has no default semantics beyond `T*` it can be used without changing any code using it and without affecting ABIs.
6168 It is simply a (most valuable) indicator to programmers and analysis tools.
6169 For example, if an `owner<T>` is a member of a class, that class better have a destructor that `delete`s it.
6173 Returning a (raw) pointer imposes a life-time management burden on the caller; that is, who deletes the pointed-to object?
6175 Gadget* make_gadget(int n)
6177 auto p = new Gadget{n};
6184 auto p = make_gadget(n); // remember to delete p
6189 In addition to suffering from then 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:'
6191 Gadget make_gadget(int n)
6200 This rule applies to factory functions.
6204 If pointer semantics is required (e.g., because the return type needs to refer to a base class of a class hierarchy (an interface)), return a "smart pointer."
6208 * (Simple) Warn on `delete` of a raw pointer that is not an `owner<T>`.
6209 * (Moderate) Warn on failure to either `reset` or explicitly `delete` an `owner<T>` pointer on every code path.
6210 * (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
6211 * (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor.
6212 Suggest considering returning it by value instead.
6214 ### <a name="Rr-ref"></a> R.4: A raw reference (a `T&`) is non-owning
6218 There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning.
6219 We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.
6225 int& r = *new int{7}; // bad: raw owning reference
6227 delete &r; // bad: violated the rule against deleting raw pointers
6230 **See also**: [The raw pointer rule](#Rr-ptr)
6234 See [the raw pointer rule](#Rr-ptr)
6236 ### <a name="Rr-scoped"></a> R.5: Prefer scoped objects
6240 A scoped object is a local object, a global object, or a member.
6241 This implies that there is no separate allocation and deallocation cost in excess that already used for the containing scope or object.
6242 The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.
6246 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:
6248 void some_function(int n)
6250 auto p = new Gadget{n};
6255 Instead, use a local variable:
6257 void some_function(int n)
6265 * (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.
6266 * (Simple) Warn if a local `Unique_ptr` or `Shared_ptr` is not moved, copied, reassigned or `reset` before its lifetime ends.
6268 ### <a name="Rr-global"></a> R.6: Avoid non-`const` global variables
6272 Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects.
6273 They are a notable source of errors.
6275 **Warning**: The initialization of global objects is not totally ordered. If you use a global object initialize it with a constant.
6277 **Exception**: a global object is often better than a singleton.
6279 **Exception**: An immutable (`const`) global does not introduce the problems we try to avoid by banning global objects.
6283 (??? NM: Obviously we can warn about non-const statics....do we want to?)
6285 ## <a name="SS-alloc"></a> R.alloc: Allocation and deallocation
6287 ### <a name="Rr-mallocfree"></a> R.10: Avoid `malloc()` and `free()`
6291 `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`.
6303 Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));
6304 // p1 may be nullptr
6305 // *p1 is not initialized; in particular, that string isn't a string, but a string-sizes bag of bits
6307 auto p2 = new Record;
6309 // unless an exception is thrown, *p2 is default initialized
6310 auto p3 = new(nothrow) Record;
6311 // p3 may be nullptr; if not, *p2 is default initialized
6315 delete p1; // error: cannot delete object allocated by malloc()
6316 free(p2); // error: cannot free() object allocated by new
6319 In some implementations that `delete` and that `free()` might work, or maybe they will cause run-time errors.
6323 There are applications and sections of code where exceptions are not acceptable.
6324 Some of the best such example are in life-critical hard real-time code.
6325 Beware that many bans on exception use are based on superstition (bad)
6326 or by concerns for older code bases with unsystematics resource management (unfortunately, but sometimes necessary).
6327 In such cases, consider the `nothrow` versions of `new`.
6331 Flag explicit use of `malloc` and `free`.
6333 ### <a name="Rr-newdelete"></a> R.11: Avoid calling `new` and `delete` explicitly
6337 The pointer returned by `new` should belong to a resource handle (that can call `delete`).
6338 If the pointer returned from `new` is assigned to a plain/naked pointer, the object can be leaked.
6342 In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management)
6343 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?
6344 The bug may be latent: it may emerge only during maintenance.
6345 If you have a naked `new`, you probably need a naked `delete` somewhere, so you probably have a bug.
6349 (Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead.
6351 ### <a name="Rr-immediate-alloc"></a> R.12: Immediately give the result of an explicit resource allocation to a manager object
6355 If you don't, an exception or a return may lead to a leak.
6359 void f(const string& name)
6361 FILE* f = fopen(name, "r"); // open the file
6362 vector<char> buf(1024);
6363 auto _ = finally([] { fclose(f); }) // remember to close the file
6367 The allocation of `buf` may fail and leak the file handle.
6371 void f(const string& name)
6373 ifstream {name, "r"}; // open the file
6374 vector<char> buf(1024);
6378 The use of the file handle (in `ifstream`) is simple, efficient, and safe.
6382 * Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)
6384 ### <a name="Rr-single-alloc"></a> R.13: Perform at most one explicit resource allocation in a single expression statement
6388 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.
6392 void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);
6394 This `fun` can be called like this:
6396 fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d))); // BAD: potential leak
6398 This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments.
6399 In particular, the compiler can interleave execution of the two expressions:
6400 Memory allocation (by calling `operator new`) could be done first for both objects, followed by attempts to call the two `Widget` constructors.
6401 If one of the constructor calls throws an exception, then the other object's memory will never be released!
6403 This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement.
6406 shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
6407 fun(sp1, new Widget(c, d));
6409 The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:
6411 fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best
6413 Write your own factory wrapper if there is not one already.
6417 * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
6419 ### <a name="Rr-ap"></a> R.14: ??? array vs. pointer parameter
6423 An array decays to a pointer, thereby losing its size, opening the opportunity for range errors.
6427 ??? what do we recommend: f(int*[]) or f(int**) ???
6429 **Alternative**: Use `array_view` to preserve size information.
6433 Flag `[]` parameters.
6435 ### <a name="Rr-pair"></a> R.15: Always overload matched allocation/deallocation pairs
6439 Otherwise you get mismatched operations and chaos.
6445 void* operator new(size_t s);
6446 void operator delete(void*);
6452 If you want memory that cannot be deallocated, `=delete` the deallocation operation.
6453 Don't leave it undeclared.
6457 Flag incomplete pairs.
6459 ## <a name="SS-smart"></a> R.smart: Smart pointers
6461 ### <a name="Rr-owner"></a> Rule R.20: Use `unique_ptr` or `shared_ptr` to represent ownership
6465 They can prevent resource leaks.
6474 X* p1 { new X }; // see also ???
6475 unique_ptr<T> p2 { new X }; // unique ownership; see also ???
6476 shared_ptr<T> p3 { new X }; // shared ownership; see also ???
6479 This will leak the object used to initialize `p1` (only).
6483 (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
6485 ### <a name="Rr-unique"></a> Rule R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership
6489 A `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).
6493 This needlessly adds and maintains a reference count.
6497 shared_ptr<Base> base = make_shared<Derived>();
6498 // use base locally, without copying it -- refcount never exceeds 1
6503 This is more efficient:
6507 unique_ptr<Base> base = make_unique<Derived>();
6513 (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.
6515 ### <a name="Rr-make_shared"></a> R.22: Use `make_shared()` to make `shared_ptr`s
6519 If you first make an object and then gives 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.
6525 shared_ptr<X> p1 { new X{2} }; // bad
6526 auto p = make_shared<X>(2); // good
6528 The `make_shared()` version mentions `X` only once, so it is usually shorter (as well as faster) than the version with the explicit `new`.
6532 (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`.
6534 ### <a name="Rr-make_unique"></a> Rule R.23: Use `make_unique()` to make `unique_ptr`s
6538 For convenience and consistency with `shared_ptr`.
6542 `make_unique()` is C++14, but widely available (as well as simple to write).
6546 (Simple) Warn if a `Shared_ptr` is constructed from the result of `new` rather than `make_unique`.
6548 ### <a name="Rr-weak_ptr"></a> R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s
6552 `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
6553 be able to destroy a cyclic structure.
6561 ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.)
6562 ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it.
6563 You could "temporarily share ownership simply by using another `stared_ptr`.)
6567 ???probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr`
6569 ### <a name="Rr-smartptrparam"></a> R.30: Take smart pointers as parameters only to explicitly express lifetime semantics
6573 Accepting a smart pointer to a `widget` is wrong if the function just needs the `widget` itself.
6574 It should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
6575 A function that does not manipulate lifetime should take raw pointers or references instead.
6580 void f(shared_ptr<widget>& w)
6583 use(*w); // only use of w -- the lifetime is not used at all
6588 shared_ptr<widget> my_widget = /*...*/;
6591 widget stack_widget;
6592 f(stack_widget); // error
6605 shared_ptr<widget> my_widget = /*...*/;
6608 widget stack_widget;
6609 f(stack_widget); // ok -- now this works
6613 * (Simple) Warn if a function takes a parameter of a type that is a `Unique_ptr` or `Shared_ptr` and the function only calls any of: `operator*`, `operator->` or `get()`).
6614 Suggest using a `T*` or `T&` instead.
6616 ### <a name="Rr-smart"></a> R.31: If you have non-`std` smart pointers, follow the basic pattern from `std`
6620 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.
6621 You want the rules to work on all the smart pointers you use.
6623 Any type (including primary template or specialization) that overloads unary `*` and `->` is considered a smart pointer:
6625 * If it is copyable, it is recognized as a reference-counted `Shared_ptr`.
6626 * If it not copyable, it is recognized as a unique `Unique_ptr`.
6630 // use Boost's intrusive_ptr
6631 #include <boost/intrusive_ptr.hpp>
6632 void f(boost::intrusive_ptr<widget> p) // error under rule 'sharedptrparam'
6637 // use Microsoft's CComPtr
6638 #include <atlbase.h>
6639 void f(CComPtr<widget> p) // error under rule 'sharedptrparam'
6644 Both cases are an error under the [`sharedptrparam` guideline](#Rr-smartptrparam):
6645 `p` is a `Shared_ptr`, but nothing about its sharedness is used here and passing it by value is a silent pessimization;
6646 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&`.
6647 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.
6649 ### <a name="Rr-uniqueptrparam"></a> R.32: Take a `unique_ptr<widget>` parameter to express that a function assumes ownership of a `widget`
6653 Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer.
6657 void sink(unique_ptr<widget>); // consumes the widget
6659 void sink(widget*); // just uses the widget
6663 void thinko(const unique_ptr<widget>&); // usually not what you want
6667 * (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.
6668 * (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.
6669 * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr<T>` parameter by rvalue reference. Suggest using pass by value instead.
6671 ### <a name="Rr-reseat"></a> R.33: Take a `unique_ptr<widget>&` parameter to express that a function reseats the`widget`
6675 Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics.
6679 "reseat" means "making a reference or a smart pointer refer to a different object."
6683 void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer
6687 void thinko(const unique_ptr<widget>&); // usually not what you want
6691 * (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.
6692 * (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.
6693 * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr<T>` parameter by rvalue reference. Suggest using pass by value instead.
6695 ### <a name="Rr-sharedptrparam-owner"></a> R.34: Take a `shared_ptr<widget>` parameter to express that a function is part owner
6699 This makes the function's ownership sharing explicit.
6703 void share(shared_ptr<widget>); // share – "will" retain refcount
6705 void reseat(shared_ptr<widget>&); // "might" reseat ptr
6707 void may_share(const shared_ptr<widget>&); // "might" retain refcount
6711 * (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.
6712 * (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.
6713 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
6715 ### <a name="Rr-sharedptrparam"></a> R.35: Take a `shared_ptr<widget>&` parameter to express that a function might reseat the shared pointer
6719 This makes the function's reseating explicit.
6723 "reseat" means "making a reference or a smart pointer refer to a different object."
6727 void share(shared_ptr<widget>); // share – "will" retain refcount
6729 void reseat(shared_ptr<widget>&); // "might" reseat ptr
6731 void may_share(const shared_ptr<widget>&); // "might" retain refcount
6735 * (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.
6736 * (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.
6737 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
6739 ### <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 ???
6743 This makes the function's ??? explicit.
6747 void share(shared_ptr<widget>); // share – "will" retain refcount
6749 void reseat(shared_ptr<widget>&); // "might" reseat ptr
6751 void may_share(const shared_ptr<widget>&); // "might" retain refcount
6755 * (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.
6756 * (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.
6757 * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr<T>` by rvalue reference. Suggesting taking it by value instead.
6759 ### <a name="Rr-smartptrget"></a> R.37: Do not pass a pointer or reference obtained from an aliased smart pointer
6763 Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer.
6764 Functions should prefer to pass raw pointers and references down call chains.
6765 At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive.
6766 You need to be sure that smart pointer cannot be inadvertently be reset or reassigned from within the call tree below
6770 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.
6776 // global (static or heap), or aliased local...
6777 shared_ptr<widget> g_p = ...;
6787 g_p = ... ; // oops, if this was the last shared_ptr to that widget, destroys the widget
6790 The following should not pass code review:
6794 f(*g_p); // BAD: passing pointer or reference obtained from a nonlocal smart pointer
6795 // that could be inadvertently reset somewhere inside f or it callees
6796 g_p->func(); // BAD: same reason, just passing it as a "this" pointer
6799 The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:
6803 auto pin = g_p; // cheap: 1 increment covers this entire function and all the call trees below us
6804 f(*pin); // GOOD: passing pointer or reference obtained from a local unaliased smart pointer
6805 pin->func(); // GOOD: same reason
6810 * (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.
6812 # <a name="S-expr"></a> ES: Expressions and Statements
6814 Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements.
6816 For naming, commenting, and indentation rules, see [NL: Naming and layout](#S-naming).
6820 * [ES.1: Prefer the standard library to other libraries and to "handcrafted code"](#Res-lib)
6821 * [ES.2: Prefer suitable abstractions to direct use of language features](#Res-abstr)
6825 * [ES.5: Keep scopes small](#Res-scope)
6826 * [ES.6: Declare names in for-statement initializers and conditions to limit scope](#Res-cond)
6827 * [ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer](#Res-name-length)
6828 * [ES.8: Avoid similar-looking names](#Res-name-similar)
6829 * [ES.9: Avoid `ALL_CAPS` names](#Res-!CAPS)
6830 * [ES.10: Declare one name (only) per declaration](#Res-name-one)
6831 * [ES.11: Use `auto` to avoid redundant repetition of type names](#Res-auto)
6832 * [ES.20: Always initialize an object](#Res-always)
6833 * [ES.21: Don't introduce a variable (or constant) before you need to use it](#Res-introduce)
6834 * [ES.22: Don't declare a variable until you have a value to initialize it with](#Res-init)
6835 * [ES.23: Prefer the `{}`-initializer syntax](#Res-list)
6836 * [ES.24: Use a `unique_ptr<T>` to hold pointers in code that may throw](#Res-unique)
6837 * [ES.25: Declare an object `const` or `constexpr` unless you want to modify its value later on](#Res-const)
6838 * [ES.26: Don't use a variable for two unrelated purposes](#Res-recycle)
6839 * [ES.27: Use `std::array` or `stack_array` for arrays on the stack](#Res-stack)
6840 * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init)
6841 * [ES.30: Don't use macros for program text manipulation](#Res-macros)
6842 * [ES.31: Don't use macros for constants or "functions"](#Res-macros2)
6843 * [ES.32: Use `ALL_CAPS` for all macro names](#Res-CAPS!)
6844 * [ES.40: Don't define a (C-style) variadic function](#Res-ellipses)
6848 * [ES.40: Avoid complicated expressions](#Res-complicated)
6849 * [ES.41: If in doubt about operator precedence, parenthesize](#Res-parens)
6850 * [ES.42: Keep use of pointers simple and straightforward](#Res-ptr)
6851 * [ES.43: Avoid expressions with undefined order of evaluation](#Res-order)
6852 * [ES.44: Don't depend on order of evaluation of function arguments](#Res-order-fct)
6853 * [ES.45: Avoid narrowing conversions](#Res-narrowing)
6854 * [ES.46: Avoid "magic constants"; use symbolic constants](#Res-magic)
6855 * [ES.47: Use `nullptr` rather than `0` or `NULL`](#Res-nullptr)
6856 * [ES.48: Avoid casts](#Res-casts)
6857 * [ES.49: If you must use a cast, use a named cast](#Res-casts-named)
6858 * [ES.50: Don't cast away `const`](#Res-casts-const)
6859 * [ES.55: Avoid the need for range checking](#Res-range-checking)
6860 * [ES.60: Avoid `new` and `delete[]` outside resource management functions](#Res-new)
6861 * [ES.61: delete arrays using `delete[]` and non-arrays using `delete`](#Res-del)
6862 * [ES.62: Don't compare pointers into different arrays](#Res-arr2)
6866 * [ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice](#Res-switch-if)
6867 * [ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice](#Res-for-range)
6868 * [ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable](#Res-for-while)
6869 * [ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable](#Res-while-for)
6870 * [ES.74: Prefer to declare a loop variable in the initializer part of as `for`-statement](#Res-for-init)
6871 * [ES.75: Avoid `do`-statements](#Res-do)
6872 * [ES.76: Avoid `goto`](#Res-goto)
6873 * [ES.77: ??? `continue`](#Res-continue)
6874 * [ES.78: ??? `break`](#Res-break)
6875 * [ES.79: ??? `default`](#Res-default)
6876 * [ES.85: Make empty statements visible](#Res-empty)
6880 * [ES.100: Don't mix signed and unsigned arithmetic](#Res-mix)
6881 * [ES.101: use unsigned types for bit manipulation](#Res-unsigned)
6882 * [ES.102: Used signed types for arithmetic](#Res-signed)
6883 * [ES.103: Don't overflow](#Res-overflow)
6884 * [ES.104: Don't underflow](#Res-underflow)
6885 * [ES.105: Don't divide by zero](#Res-zero)
6887 ### <a name="Res-lib"></a> ES.1: Prefer the standard library to other libraries and to "handcrafted code"
6891 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.
6892 The ISO C++ standard library is among the most widely know and best tested libraries.
6893 It is available as part of all C++ Implementations.
6897 auto sum = accumulate(begin(a), end(a), 0.0); // good
6899 a range version of `accumulate` would be even better:
6901 auto sum = accumulate(v, 0.0); // better
6903 but don't hand-code a well-known algorithm:
6905 int max = v.size(); // bad: verbose, purpose unstated
6907 for (int i = 0; i < max; ++i)
6910 **Exception**: 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.
6914 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
6916 ### <a name="Res-abstr"></a> ES.2: Prefer suitable abstractions to direct use of language features
6920 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.
6924 vector<string> read1(istream& is) // good
6927 for (string s; is >> s;)
6932 The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:
6934 char** read2(istream& is, int maxelem, int maxstring, int* nread) // bad: verbose and incomplete
6936 auto res = new char*[maxelem];
6938 while (is && elemcount < maxelem) {
6939 auto s = new char[maxstring];
6940 is.read(s, maxstring);
6941 res[elemcount++] = s;
6947 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.
6951 Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
6953 ## ES.dcl: Declarations
6955 A declaration is a statement. a declaration introduces a name into a scope and may cause the construction of a named object.
6957 ### <a name="Res-scope"></a> ES.5: Keep scopes small
6961 Readability. Minimize resource retention. Avoid accidental misuse of value.
6963 **Alternative formulation**: Don't declare a name in an unnecessarily large scope.
6969 int i; // bad: i is needlessly accessible after loop
6970 for (i = 0; i < 20; ++i) { /* ... */ }
6971 // no intended use of i here
6972 for (int i = 0; i < 20; ++i) { /* ... */ } // good: i is local to for-loop
6974 if (auto pc = dynamic_cast<Circle*>(ps)) { // good: pc is local to if-statement
6975 // ...deal with Circle ...
6978 // ... handle error ...
6984 void use(const string& name)
6986 string fn = name+".txt";
6990 // ... 200 lines of code without intended use of fn or is ...
6993 This function is by most measure too long anyway, but the point is that the used by `fn` and the file handle held by `is`
6994 are retained for much longer than needed and that unanticipated use of `is` and `fn` could happen later in the function.
6995 In this case, it might be a good ide to factor out the read:
6997 void fill_record(Record& r, const string& name)
6999 string fn = name+".txt";
7005 void use(const string& name)
7008 fill_record(r, name);
7009 // ... 200 lines of code ...
7012 I am assuming that `Record` is large and doesn't have a good move operation so that an out-parameter is preferable to returning a `Record`.
7016 * Flag loop variable declared outside a loop and not used after the loop
7017 * Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
7019 ### <a name="Res-cond"></a> ES.6: Declare names in for-statement initializers and conditions to limit scope
7023 Readability. Minimize resource retention.
7029 for (string s; cin >> s;)
7032 for (int i = 0; i < 20; ++i) { // good: i is local to for-loop
7036 if (auto pc = dynamic_cast<Circle*>(ps)) { // good: pc is local to if-statement
7037 // ...deal with Circle ...
7040 // ... handle error ...
7046 * Flag loop variables declared before the loop and not used after the loop
7047 * (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose.
7049 ### <a name="Res-name-length"></a> ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer
7053 Readability. Lowering the chance of clashes between unrelated non-local names.
7057 Conventional short, local names increase readability:
7059 template<typename T> // good
7060 void print(ostream& os, const vector<T>& v)
7062 for (int i = 0; i < v.end(); ++i)
7066 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
7068 template<typename Element_type> // bad: verbose, hard to read
7069 void print(ostream& target_stream, const vector<Element_type>& current_vector)
7071 for (int current_element_index = 0;
7072 current_element_index < current_vector.end();
7073 ++current_element_index
7075 target_stream << current_vector[i] << '\n';
7078 Yes, it is a caricature, but we have seen worse.
7082 Unconventional and short non-local names obscure code:
7084 void use1(const string& s)
7087 tt(s); // bad: what is tt()?
7091 Better, give non-local entities readable names:
7093 void use1(const string& s)
7096 trim_tail(s); // better
7100 Here, there is a chance that the reader knows what `trim_tail` means and that the reader can remember it after looking it up.
7104 Argument names of large functions are de facto non-local and should be meaningful:
7106 void complicated_algorithm(vector<Record>&vr, const vector<int>& vi, map<string, int>& out)
7107 // read from events in vr (marking used Records) for the indices in vi placing (name, index) pairs into out
7109 // ... 500 lines of code using vr, vi, and out ...
7112 We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.
7116 Check length of local and non-local names. Also take function length into account.
7118 ### <a name="Res-name-similar"></a> ES.8: Avoid similar-looking names
7122 Such names slow down comprehension and increase the likelihood of error.
7126 if (readable(i1 + l1 + ol + o1 + o0 + ol + o1 + I0 + l0)) surprise();
7130 Check names against a list of known confusing letter and digit combinations.
7132 ### <a name="Res-!CAPS"></a> ES.9: Avoid `ALL_CAPS` names
7136 Such names are commonly used for macros. Thus, ALL_CAPS name are vulnerable to unintended macro substitution.
7140 // somewhere in some header:
7143 // somewhere else in some other header:
7144 enum Coord { N, NE, NW, S, SE, SW, E, W };
7146 // somewhere third in some poor programmer's .cpp:
7147 switch (direction) {
7157 Do not use `ALL_CAPS` for constants just because constants used to be macros.
7161 Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names.
7163 ### <a name="Res-name-one"></a> ES.10: Declare one name (only) per declaration
7167 One-declaration-per line increases readability and avoid mistake related to the C/C++ grammar. It leaves room for a `//`-comment.
7171 char *p, c, a[7], *pp[7], **aa[10]; // yuck!
7173 **Exception**: a function declaration can contain several function argument declarations.
7177 template <class InputIterator, class Predicate>
7178 bool any_of(InputIterator first, InputIterator last, Predicate pred);
7180 or better using concepts:
7182 bool any_of(InputIterator first, InputIterator last, Predicate pred);
7186 double scalbn(double x, int n); // OK: x*pow(FLT_RADIX, n); FLT_RADIX is usually 2
7190 double scalbn( // better: x*pow(FLT_RADIX, n); FLT_RADIX is usually 2
7191 double x, // base value
7197 double scalbn(double base, int exponent); // better: base*pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
7201 Flag non-function arguments with multiple declarators involving declarator operators (e.g., `int* p, q;`)
7203 ### <a name="Res-auto"></a> ES.11: Use `auto` to avoid redundant repetition of type names
7207 * Simple repetition is tedious and error prone.
7208 * When you us `auto`, the name of the declared entity is in a fixed position in the declaration, increasing readability.
7209 * In a template function declaration the return type can be a member type.
7215 auto p = v.begin(); // vector<int>::iterator
7217 auto h = t.future();
7218 auto q = new int[s];
7219 auto f = [](int x){ return x + 10; };
7221 In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
7226 auto Container<T>::first() -> Iterator; // Container<T>::Iterator
7228 **Exception**: Avoid `auto` for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.
7232 auto lst = { 1, 2, 3 }; // lst is an initializer list (obviously)
7233 auto x{1}; // x is an int (after correction of the C++14 standard; initializer_list in C++11)
7237 When concepts become available, we can (and should) be more specific about the type we are deducing:
7240 ForwardIterator p = algo(x, y, z);
7244 Flag redundant repetition of type names in a declaration.
7246 ### <a name="Res-always"></a> ES.20: Always initialize an object
7250 Avoid used-before-set errors and their associated undefined behavior.
7254 void use(int arg) // bad: uninitialized variable
7258 i = 7; // initialize i
7261 No, `i = 7` does not initialize `i`; it assigns to it. Also, `i` can be read in the `...` part. Better:
7263 void use(int arg) // OK
7265 int i = 7; // OK: initialized
7266 string s; // OK: default initialized
7272 It you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization.
7273 However, beware that this may leave uninitialized data beyond the input - and that has been a fertile source of errors and security breaches:
7275 constexpr int max = 8*1024;
7276 int buf[max]; // OK, but suspicious
7279 The cost of initializing that array could be significant in some situations.
7280 However, such examples do tend to leave uninitialized variables accessible, so they should be treated with suspicion.
7282 constexpr int max = 8*1024;
7283 int buf[max] = {0}; // better in some situations
7286 When feasible use a library function that is know not to overflow. For example:
7288 string s; // s is default initialized to ""
7289 cin >> s; // s expands to hold the string
7291 Don't consider simple variables that are targets for input operations exceptions to this rule:
7297 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.
7299 int i2 = 0; // better
7303 A good optimizer should know about input operations and eliminate the redundant operation.
7307 Sometimes, we want to initialize a set of variables with a call to a function that returns several values.
7308 That can lead to uninitialized variables (exceptly as for input operations):
7312 tie(ec, v) = get_value(); // get_value() returns a pair<error_code, Value>
7316 Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable.
7320 auto p = get_value(); // get_value() returns a pair<error_code, Value>
7328 auto p = get_value(); // get_value() returns a pair<error_code, Value>
7329 if (p.first) throw Bad_value{p.first};
7333 **See also**: [ES.28](#Res-lambda-init)
7337 * Flag every uninitialized variable.
7338 Don't flag variables of user-defined types with default constructors.
7339 * Check that the uninitialized buffer is read into *immediately* after declaration.
7341 ### <a name="Res-introduce"></a> ES.21: Don't introduce a variable (or constant) before you need to use it
7345 Readability. To limit the scope in which the variable can be used.
7350 // ... no use of x here ...
7355 Flag declaration that distant from their first use.
7357 ### <a name="Res-init"></a> ES.22: Don't declare a variable until you have a value to initialize it with
7361 Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment.
7366 // ... no use of s here ...
7371 SomeLargeType var; // ugly CaMeLcAsEvArIaBlE
7373 if (cond) // some non-trivial condition
7375 else if (cond2 || !cond3) {
7380 for (auto& e : something)
7384 // use var; that this isn't done too early can be enforced statically with only control flow
7386 This would be fine if there was a default initialization for `SomeLargeType` that wasn't too expensive.
7387 Otherwise, a programmer might very well wonder if every possible path through the maze of conditions has been covered.
7388 If not, we have a "use before set" bug. This is a maintenance trap.
7390 For initializers of moderate complexity, including for `const` variables, consider using a lambda to express the initializer; see [ES.28](#Res-lambda-init).
7394 * Flag declarations with default initialization that are assigned to before they are first read.
7395 * Flag any complicated computation after an uninitialized variable and before its use.
7397 ### <a name="Res-list"></a> ES.23: Prefer the `{}` initializer syntax
7401 The rules for `{}` initialization is simpler, more general, and safer than for other forms of initialization, and unambiguous.
7406 vector<int> v = {1, 2, 3, 4, 5, 6};
7410 For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes:
7412 vector<int> v1(10); // vector of 10 elements with the default value 0
7413 vector<int> v2 {10}; // vector of 1 element with the value 10
7417 `{}`-initializers do not allow narrowing conversions.
7421 int x {7.9}; // error: narrowing
7422 int y = 7.9; // OK: y becomes 7. Hope for a compiler warning
7426 `{}` initialization can be used for all initialization; other forms of initialization can't:
7428 auto p = new vector<int> {1, 2, 3, 4, 5}; // initialized vector
7429 D::D(int a, int b) :m{a, b} { // member initializer (e.g., m might be a pair)
7432 X var {}; // initialize var to be empty
7434 int m {7}; // default initializer for a member
7440 Initialization of a variable declared `auto` with a single value `{v}` surprising results until recently:
7442 auto x1 {7}; // x1 is an int with the value 7
7443 auto x2 = {7}; // x2 is an initializer_int<int> with an element 7
7445 auto x11 {7, 8}; // error: two initializers
7446 auto x22 = {7, 8}; // x2 is an initializer_int<int> with elements 7 and 8
7450 Use `={...}` if you really want an `initializer_list<T>`
7452 auto fib10 = {0, 1, 2, 3, 5, 8, 13, 25, 38, 63}; // fib10 is a list
7456 template<typename T>
7459 T x1(1); // T initialized with 1
7460 T x0(); // bad: function declaration (often a mistake)
7462 T y1 {1}; // T initialized with 1
7463 T y0 {}; // default initialized T
7467 **See also**: [Discussion](#???)
7473 * Don't flag uses of `=` for simple initializers.
7474 * Look for `=` after `auto` has been seen.
7476 ### <a name="Res-unique"></a> ES.24: Use a `unique_ptr<T>` to hold pointers in code that may throw
7480 Using `std::unique_ptr` is the simplest way to avoid leaks. And it is free compared to alternatives
7486 auto p1 = make_unique<int>(7); // OK
7487 int* p2 = new int{7}; // bad: might leak
7493 If `leak == true` the object pointer to by `p2` is leaked and the object pointed to by `p1` is not.
7497 Look for raw pointers that are targets of `new`, `malloc()`, or functions that may return such pointers.
7499 ### <a name="Res-const"></a> ES.25: Declare an objects `const` or `constexpr` unless you want to modify its value later on
7503 That way you can't change the value by mistake. That way may offer the compiler optimization opportunities.
7509 const int bufmax = 2 * n + 2; // good: we can't change bufmax by accident
7510 int xmax = n; // suspicious: is xmax intended to change?
7516 Look to see if a variable is actually mutated, and flag it if not. Unfortunately, it may be impossible to detect when a non-`const` was not intended to vary.
7518 ### <a name="Res-recycle"></a> ES.26: Don't use a variable for two unrelated purposes
7529 for (i = 0; i < 20; ++i) { /* ... */ }
7530 for (i = 0; i < 200; ++i) { /* ... */ } // bad: i recycled
7535 Flag recycled variables.
7537 ### <a name="Res-stack"></a> ES.27: Use `std::array` or `stack_array` for arrays on the stack
7541 They are readable and don't implicitly convert to pointers.
7542 They are not confused with non-standard extensions of built-in arrays.
7552 int a2[m]; // error: not ISO C++
7558 The definition of `a1` is legal C++ and has always been.
7559 There is a lot of such code.
7560 It is error-prone, though, especially when the bound is non-local.
7561 Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.).
7562 The definition of `a2` is C but not C++ and is considered a security risk
7572 stack_array<int> a2(m);
7578 * Flag arrays with non-constant bounds (C-style VLAs)
7579 * Flag arrays with non-local constant bounds
7581 ### <a name="Res-lambda-init"></a> ES.28: Use lambdas for complex initialization, especially of `const` variables
7585 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.
7589 widget x; // should be const, but:
7590 for (auto i = 2; i <= N; ++i) { // this could be some
7591 x += some_obj.do_something_with(i); // arbitrarily long code
7592 } // needed to initialize x
7593 // from here, x should be const, but we can’t say so in code in this style
7597 const widget x = [&]{
7598 widget val; // assume that widget has a default constructor
7599 for (auto i = 2; i <= N; ++i) { // this could be some
7600 val += some_obj.do_something_with(i); // arbitrarily long code
7601 } // needed to initialize x
7608 if (!in) return ""; // default
7610 for (char c : in >> c)
7615 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.
7619 owner<istream&> in = [&]{
7621 case default: owned=false; return cin;
7622 case command_line: owned=true; return *new istringstream{argv[2]};
7623 case file: owned=true; return *new ifstream{argv[2]};
7628 Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it.
7630 ### <a name="Res-macros"></a> ES.30: Don't use macros for program text manipulation
7634 Macros are a major source of bugs.
7635 Macros don't obey the usual scope and type rules.
7636 Macros ensure that the human reader see something different from whet the compiler sees.
7637 Macros complicates tool building.
7641 #define Case break; case /* BAD */
7643 This innocuous-looking macro makes a single lower case `c` instead of a `C` into a bad flow-control bug.
7647 This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc.
7651 Scream when you see a macro that isn't just use for source control (e.g., `#ifdef`)
7653 ### <a name="Res-macros2"></a> ES.31: Don't use macros for constants or "functions"
7657 Macros are a major source of bugs.
7658 Macros don't obey the usual scope and type rules.
7659 Macros don't obey the usual rules for argument passing.
7660 Macros ensure that the human reader see something different from whet the compiler sees.
7661 Macros complicates tool building.
7666 #define SQUARE(a, b) (a*b)
7668 Even if we hadn't left a well-know bug in `SQUARE` there are much better behaved alternatives; for example:
7670 constexpr double pi = 3.14;
7671 template<typename T> T square(T a, T b) { return a*b; }
7675 Scream when you see a macro that isn't just use for source control (e.g., `#ifdef`)
7677 ### <a name="Res-CAPS!"></a> ES.32: Use `ALL_CAPS` for all macro names
7681 Convention. Readability. Distinguishing macros.
7685 #define forever for(;;) /* very BAD */
7687 #define FOREVER for(;;) /* Still evil, but at least visible to humans */
7691 Scream when you see a lower case macro.
7693 ### <a name="Res-ellipses"></a> ES.40: Don't define a (C-style) variadic function
7697 Not type safe. Requires messy cast-and-macro-laden code to get working right.
7703 **Alternative**: Overloading. Templates. Variadic templates.
7707 There are rare used of variadic functions in SFINAE code, but those don't actually run and don't need the `<vararg>` implementation mess.
7711 Flag definitions of C-style variadic functions.
7713 ## ES.stmt: Statements
7715 Statements control the flow of control (except for function calls and exception throws, which are expressions).
7717 ### <a name="Res-switch-if"></a> ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice
7722 * Efficiency: A `switch` compares against constants and is usually better optimized than a series of tests in an `if`-`then`-`else` chain.
7723 * a `switch` is enables some heuristic consistency checking. For example, has all values of an `enum` been covered? If not, is there a `default`?
7729 switch (n) { // good
7739 if (n == 0) // bad: if-then-else chain comparing against a set of constants
7747 Flag if-then-else chains that check against constants (only).
7749 ### <a name="Res-for-range"></a> ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice
7753 Readability. Error prevention. Efficiency.
7757 for (int i = 0; i < v.size(); ++i) // bad
7758 cout << v[i] << '\n';
7760 for (auto p = v.begin(); p != v.end(); ++p) // bad
7763 for (auto& x : v) // OK
7766 for (int i = 1; i < v.size(); ++i) // touches two elements: can't be a range-for
7767 cout << v[i] + v[-1] << '\n';
7769 for (int i = 1; i < v.size(); ++i) // possible side-effect: can't be a range-for
7770 cout << f(&v[i]) << '\n';
7772 for (int i = 1; i < v.size(); ++i) { // body messes with loop variable: can't be a range-for
7774 ++i; // skip even elements
7776 cout << v[i] << '\n';
7779 A human or a good static analyzer may determine that there really isn't a side effect on `v` in `f(&v[i])` so that the loop can be rewritten.
7781 "Messing with the loop variable" in the body of a loop is typically best avoided.
7785 Don't use expensive copies of the loop variable of a range-`for` loop:
7787 for (string s : vs) // ...
7789 This will copy each elements of `vs` into `s`. Better
7791 for (string& s : vs) // ...
7795 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 for loop.
7797 ### <a name="Res-for-while"></a> ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable
7801 Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited.
7805 for (int i = 0; i < vec.size(); i++) {
7812 while (i < vec.size()) {
7821 ### <a name="Res-while-for"></a> ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable
7835 ### <a name="Res-for-init"></a> ES.74: Prefer to declare a loop variable in the initializer part of as `for`-statement
7839 Limit the loop variable visibility to the scope of the loop.
7840 Avoid using the loop variable for other purposes after the loop.
7844 for (int i = 0; i < 100; ++i) { // GOOD: i var is visible only inside the loop
7848 ##### Example, don't
7850 int j; // BAD: j is visible outside the loop
7851 for (j = 0; j < 100; ++j) {
7854 // j is still visible here and isn't needed
7856 **See also**: [Don't use a variable for two unrelated purposes](#Res-recycle)
7860 Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop.
7862 **Discussion**: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable
7863 is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc.
7865 ### <a name="Res-do"></a> ES.75: Avoid `do`-statements
7869 Readability, avoidance of errors.
7870 The termination conditions is at the end (where it can be overlooked) and the condition is not checked the first time through. ???
7884 ### <a name="Res-goto"></a> ES.76: Avoid `goto`
7888 Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code.
7892 Breaking out of a nested loop. In that case, always jump forwards.
7900 There is a fair amount of use of the C goto-exit idiom:
7910 ... common cleanup code ...
7913 This is an ad-hoc simulation of destructors. Declare your resources with handles with destructors that clean up.
7917 * 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.
7919 ### <a name="Res-continue"></a> ES.77: ??? `continue`
7933 ### <a name="Res-break"></a> ES.78: Always end a `case` with a `break`
7937 ??? loop, switch ???
7945 Multiple case labels of a single statement is OK:
7959 ### <a name="Res-default"></a> ES.79: ??? `default`
7973 ### <a name="Res-empty"></a> ES.85: Make empty statements visible
7981 for (i = 0; i < max; ++i); // BAD: the empty statement is easily overlooked
7984 for (auto x : v) { // better
7990 Flag empty statements that are not blocks and doesn't "contain" comments.
7992 ## ES.expr: Expressions
7994 Expressions manipulate values.
7996 ### <a name="Res-complicated"></a> ES.40: Avoid complicated expressions
8000 Complicated expressions are error-prone.
8004 while ((c = getc()) != -1) // bad: assignment hidden in subexpression
8006 while ((cin >> c1, cin >> c2), c1 == c2) // bad: two non-local variables assigned in a sub-expressions
8008 for (char c1, c2; cin >> c1 >> c2 && c1 == c2;) // better, but possibly still too complicated
8010 int x = ++i + ++j; // OK: iff i and j are not aliased
8012 v[i] = v[j] + v[k]; // OK: iff i != j and i != k
8014 x = a + (b = f()) + (c = g()) * 7; // bad: multiple assignments "hidden" in subexpressions
8016 x = a & b + c * d && e ^ f == 7; // bad: relies on commonly misunderstood precedence rules
8018 x = x++ + x++ + ++x; // bad: undefined behavior
8020 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.
8024 A programmer should know and use the basic rules for expressions.
8030 auto t1 = k*y; // bad: unnecessarily verbose
8033 if (0 <= x && x < max) // OK
8035 auto t1 = 0 <= x; // bad: unnecessarily verbose
8037 if (t1 && t2) // ...
8041 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:
8043 * 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
8044 * writes to aliased variables
8045 * more than N operators (and what should N be?)
8046 * reliance of subtle precedence rules
8047 * uses undefined behavior (can we catch all undefined behavior?)
8048 * implementation defined behavior?
8051 ### <a name="Res-parens"></a> ES.41: If in doubt about operator precedence, parenthesize
8055 Avoid errors. Readability. Not everyone has the operator table memorized.
8059 if (a && b == 1) // OK?
8060 if (a & b == 1) // OK?
8062 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.
8064 if (a && b == 1) // OK: means a&&(b == 1)
8065 if (a & b == 1) // bad: means (a&b) == 1
8069 You should know enough not to need parentheses for:
8071 if (a<0 || a<=max) {
8077 * Flag combinations of bitwise-logical operators and other operators.
8078 * Flag assignment operators not as the leftmost operator.
8081 ### <a name="Res-ptr"></a> ES.42: Keep use of pointers simple and straightforward
8085 Complicated pointer manipulation is a major source of errors.
8087 * Do all pointer arithmetic on an `array_view` (exception ++p in simple loop???)
8088 * Avoid pointers to pointers
8097 We need a heuristic limiting the complexity of pointer arithmetic statement.
8099 ### <a name="Res-order"></a> ES.43: Avoid expressions with undefined order of evaluation
8103 You have no idea what such code does. Portability.
8104 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.
8108 v[i] = ++i; // the result is undefined
8110 A good rule of thumb is that you should not read a value twice in an expression where you write to it.
8122 Can be detected by a good analyzer.
8124 ### <a name="Res-order-fct"></a> ES.44: Don't depend on order of evaluation of function arguments
8128 Because that order is unspecified.
8135 The call will most likely be `f(0, 1)` or `f(1, 0)`, but you don't know which. Technically, the behavior is undefined.
8139 ??? overloaded operators can lead to order of evaluation problems (shouldn't :-()
8141 f1()->m(f2()); // m(f1(), f2())
8142 cout << f1() << f2(); // operator<<(operator<<(cout, f1()), f2())
8146 Can be detected by a good analyzer.
8148 ### <a name="Res-magic"></a> ES.45: Avoid "magic constants"; use symbolic constants
8152 Unnamed constants embedded in expressions are easily overlooked and often hard to understand:
8156 for (int m = 1; m <= 12; ++m) // don't: magic constant 12
8157 cout << month[m] << '\n';
8159 No, we don't all know that there a 12 month, numbered 1..12, in a year. Better:
8161 constexpr int last_month = 12; // months are numbered 1..12
8163 for (int m = first_month; m <= last_month; ++m) // better
8164 cout << month[m] << '\n';
8166 Better still, don't expose constants:
8168 for (auto m : month)
8173 Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list.
8175 ### <a name="Res-narrowing"></a> ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions
8179 A narrowing conversion destroys information, often unexpectedly so.
8183 A key example is basic narrowing:
8186 int i = d; // bad: narrowing: i becomes 7
8187 i = (int)d; // bad: we're going to claim this is still not explicit enough
8189 void f(int x, long y, double d)
8191 char c1 = x; // bad: narrowing
8192 char c2 = y; // bad: narrowing
8193 char c3 = d; // bad: narrowing
8198 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:
8200 i = narrow_cast<int>(d); // OK (you asked for it): narrowing: i becomes 7
8201 i = narrow<int>(d); // OK: throws narrowing_error
8203 We also include lossy arithmetic casts, such as from a negative floating point type to an unsigned integral type:
8209 u = narrow_cast<unsigned>(d); // OK (you asked for it): u becomes 0
8210 u = narrow<unsigned>(d); // OK: throws narrowing_error
8214 A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions:
8216 * flag all floating-point to integer conversions (maybe only float->char and double->int. Here be dragons! we need data)
8217 * flag all long->char (I suspect int->char is very common. Here be dragons! we need data)
8218 * consider narrowing conversions for function arguments especially suspect
8220 ### <a name="Res-nullptr"></a> ES.47: Use `nullptr` rather than `0` or `NULL`
8224 Readability. Minimize surprises: `nullptr` cannot be confused with an `int`.
8232 f(0); // call f(int)
8233 f(nullptr); // call f(char*)
8237 Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation.
8239 ### <a name="Res-casts"></a> ES.48: Avoid casts
8243 Casts are a well-known source of errors. Makes some optimizations unreliable.
8251 Programmer who write casts typically assumes that they know what they are doing.
8252 In fact, they often disable the general rules for using values.
8253 Overload resolution and template instantiation usually pick the right function if there is a right function to pick.
8254 If there is not, maybe there ought to be, rather than applying a local fix (cast).
8258 Casts are necessary in a systems programming language.
8259 For example, how else would we get the address of a device register into a pointer.
8260 However, casts are seriously overused as well as a major source of errors.
8264 If you feel the need for a lot of casts, there may be a fundamental design problem.
8268 * Force the elimination of C-style casts
8269 * Warn against named casts
8270 * Warn if there are many functional style casts (there is an obvious problem in quantifying 'many').
8272 ### <a name="Res-casts-named"></a> ES.49: If you must use a cast, use a named cast
8276 Readability. Error avoidance.
8277 Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors.
8279 The named casts are:
8283 * `reinterpret_cast`
8285 * `std::move` // `move(x)` is an rvalue reference to `x`
8286 * `std::forward` // `forward(x)` is an rvalue reference to `x`
8287 * `gsl::narrow_cast` // `narrow_cast<T>(x)` is `static_cast<T>(x)`
8288 * `gsl::narrow` // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
8300 Flag C-style and functional casts.
8302 ## <a name="Res-casts-const"></a> ES.50: Don't cast away `const`
8306 It makes a lie out of `const`.
8310 Usually the reason to "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object.
8311 Examples are cashing, mnemorization, and precomputation.
8312 Such examples are often handled as well or better using `mutable` or an indirection than with a `const_cast`.
8322 ### <a name="Res-range-checking"></a> ES.55: Avoid the need for range checking
8326 Constructs that cannot overflow, don't, and usually runs faster:
8330 for (auto& x : v) // print all elements of v
8333 auto p = find(v, x); // find x in v
8337 Look for explicit range checks and heuristically suggest alternatives.
8339 ### <a name="Res-new"></a> ES.60: Avoid `new` and `delete[]` outside resource management functions
8343 Direct resource management in application code is error-prone and tedious.
8347 also known as "No naked `new`!"
8353 auto p = new X[n]; // n default constructed Xs
8358 There can be code in the `...` part that causes the `delete` never to happen.
8360 **See also**: [R: Resource management](#S-resource).
8364 Flag naked `new`s and naked `delete`s.
8366 ### <a name="Res-del"></a> ES.61: delete arrays using `delete[]` and non-arrays using `delete`
8370 That's what the language requires and mistakes can lead to resource release errors and/or memory corruption.
8376 auto p = new X[n]; // n default constructed Xs
8378 delete p; // error: just delete the object p, rather than delete the array p[]
8383 This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems.
8387 * if the `new` and the `delete` is in the same scope, mistakes can be flagged.
8388 * if the `new` and the `delete` are in a constructor/destructor pair, mistakes can be flagged.
8390 ### <a name="Res-arr2"></a> ES.62: Don't compare pointers into different arrays
8394 The result of doing so is undefined.
8402 if (&a1[5] < &a2[7]) {} // bad: undefined
8403 if (0 < &a1[5] - &a2[7]) {} // bad: undefined
8408 This example has many more problems.
8412 ## <a name="SS-numbers"></a> Arithmetic
8414 ### <a name="Res-mix"></a> ES.100: Don't mix signed and unsigned arithmetic
8418 Avoid wrong results.
8424 cout << abs(x-y) << '\n'; // wrong result
8428 Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts.
8429 This precludes consistency.
8433 Compilers already know and sometimes warn.
8435 ### <a name="Res-unsigned"></a> ES.101: use unsigned types for bit manipulation
8439 Unsigned types support bit manipulation without surprises from sign bits.
8445 **Exception**: Use unsigned types if you really want modulo arithmetic.
8451 ### <a name="Res-signed"></a> ES.102: Used signed types for arithmetic
8455 Unsigned types support bit manipulation without surprises from sign bits.
8461 **Exception**: Use unsigned types if you really want modulo arithmetic.
8467 ### <a name="Res-overflow"></a> ES.103: Don't overflow
8471 Overflow usually makes your numeric algorithm meaningless.
8472 Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
8481 a[n - 1] = 9; // bad (twice)
8485 int n = numeric_limits<int>::max();
8486 int m = n + 1; // bad
8490 int area(int h, int w) { return h * w; }
8492 auto a = area(10'000'000, 100'000'000); // bad
8494 **Exception**: Use unsigned types if you really want modulo arithmetic.
8496 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
8502 ### <a name="Res-underflow"></a> ES.104: Don't underflow
8506 Decrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.
8515 a[n - 1] = 9; // bad (twice)
8517 **Exception**: Use unsigned types if you really want modulo arithmetic.
8523 ### <a name="Res-zero"></a> ES.105: Don't divide by zero
8527 The result is undefined and probably a crash.
8531 this also applies to `%`.
8537 **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.
8543 # <a name="S-performance"></a> PER: Performance
8545 ???should this section be in the main guide???
8547 This section contains rules for people who needs high performance or low-latency.
8548 That is, rules that relates to how to use as little time and as few resources as possible to achieve a task in a predictably short time.
8549 The rules in this section are more restrictive and intrusive than what is needed for many (most) applications.
8550 Do not blindly try to follow them in general code because achieving the goals of low latency requires extra work.
8552 Performance rule summary:
8554 * [PER.1: Don't optimize without reason](#Rper-reason)
8555 * [PER.2: Don't optimize prematurely](#Rper-Knuth)
8556 * [PER.3: Don't optimize something that's not performance critical](#Rper-critical)
8557 * [PER.4: Don't assume that complicated code is necessarily faster than simple code](#Rper-simple)
8558 * [PER.5: Don't assume that low-level code is necessarily faster than high-level code](#Rper-low)
8559 * [PER.6: Don't make claims about performance without measurements](#Rper-measure)
8560 * [PER.10: Rely on the static type system](#Rper-type)
8561 * [PER.11: Move computation from run time to compile time](#Rper-Comp)
8562 * [PER.12: Eliminate redundant aliases](#Rper-alias)
8563 * [PER.13: Eliminate redundant indirections](#Rper-indirect)
8564 * [PER.14: Minimize the number of allocations and deallocations](#Rper-alloc)
8565 * [PER.15: Do not allocate on a critical branch](#Rper-alloc0)
8566 * [PER.16: Use compact data structures](#Rper-compact)
8567 * [PER.17: Declare the most used member of a time critical struct first](#Rper-struct)
8568 * [PER.18: Space is time](#Rper-space)
8569 * [PER.19: Access memory predictably](#Rper-access)
8570 * [PER.30: Avoid context switches on the critical path](#Rper-context)
8572 ### <a name="Rper-reason"></a> PER.1: Don't optimize without reason
8576 If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs.
8580 Some people optimize out of habit or because it's fun.
8584 ### <a name="Rper-Knuth"></a> PER.2: Don't optimize prematurely
8588 Elaborately optimized code is usually larger and harder to change than unoptimized code.
8592 ### <a name="Rper-critical"></a> PER.3: Don't optimize something that's not performance critical
8596 Optimizing a non-performance-critical part of a program has no effect on system performance.
8600 If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless.
8603 ### <a name="Rper-simple"></a> PER.4: Don't assume that complicated code is necessarily faster than simple code
8607 Simple code can be very fast. Optimizers sometimes do marvels with simple code
8615 ### <a name="Rper-low"></a> PER.5: Don't assume that low-level code is necessarily faster than high-level code
8619 Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code.
8627 ### <a name="Rper-measure"></a> PER.6: Don't make claims about performance without measurements
8631 The field of performance is littered with myth and bogus folklore.
8632 Modern hardware and optimizers defy naive assumptions; even experts are regularly surprised.
8636 Getting good performance measurements can be hard and require specialized tools.
8640 A few simple microbenchmarks using Unix `time` or the standard library `<chrono>` can help dispel the most obvious myths.
8641 If you can't measure your complete system accurately, at least try to measure a few of your key operations and algorithms.
8642 A profiler can help tell you which parts of your system are performance critical.
8643 Often, you will be surprised.
8647 ### <a name="Rper-type"></a> PER.10: Rely on the static type system
8651 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.
8655 ### <a name="Rper-Comp"></a> PER.11: Move computation from run time to compile time
8659 ### <a name="Rper-alias"></a> PER.12: Eliminate redundant aliases
8663 ### <a name="Rper-indirect"></a> PER.13: Eliminate redundant indirections
8667 ### <a name="Rper-alloc"></a> PER.14: Minimize the number of allocations and deallocations
8671 ### <a name="Rper-alloc0"></a> PER.15: Do not allocate on a critical branch
8675 ### <a name="Rper-compact"></a> PER.16: Use compact data structures
8679 Performance is typically dominated by memory access times.
8683 ### <a name="Rper-struct"></a> PER.17: Declare the most used member of a time critical struct first
8687 ### <a name="Rper-space"></a> PER.18: Space is time
8691 Performance is typically dominated by memory access times.
8695 ### <a name="Rper-access"></a> PER.19: Access memory predictably
8699 Performance is very sensitive to cache performance and cache algorithms favor simple (usually linear) access to adjacent data.
8703 int matrix[rows][cols];
8706 for (int c = 0; c < cols; ++c)
8707 for (int r = 0; r < rows; ++r)
8708 sum += matrix[r][c];
8711 for (int r = 0; r < rows; ++r)
8712 for (int c = 0; c < cols; ++c)
8713 sum += matrix[r][c];
8715 ### <a name="Rper-context"></a> PER.30: Avoid context switches on the critical path
8719 # <a name="S-concurrency"></a> CP: Concurrency and Parallelism
8723 Concurrency and parallelism rule summary:
8725 * [CP.1: Assume that your code will run as part of a multi-threaded program](#Rconc-multi)
8726 * [CP.2: Avoid data races](#Rconc-races)
8730 * [CP.con: Concurrency](#SScp-con)
8731 * [CP.par: Parallelism](#SScp-par)
8732 * [CP.simd: SIMD](#SScp-simd)
8733 * [CP.free: Lock-free programming](#SScp-free)
8735 ### <a name="Rconc-multi"></a> CP.1: Assume that your code will run as part of a multi-threaded program
8739 It is hard to be certain that concurrency isn't used now or sometime in the future.
8741 Libraries using threads my be used from some other part of the program.
8747 **Exception**: There are examples where code will never be run in a multi-threaded environment.
8748 However, there are also many examples where code that was "known" to never run in a multi-threaded program
8749 was run as part of a multi-threaded program. Often years later.
8750 Typically, such programs lead to a painful effort to remove data races.
8752 ### <a name="Rconc-races"></a> CP.2: Avoid data races
8756 Unless you do, nothing is guaranteed to work and subtle errors will persist.
8760 If you have any doubts about what this means, go read a book.
8764 Some is possible, do at least something.
8766 ## <a name="SScp-con"></a> CP.con: Concurrency
8770 Concurrency rule summary:
8775 ???? should there be a "use X rather than `std::async`" where X is something that would use a better specified thread pool?
8777 Speaking of concurrency, should there be a note about the dangers of `std::atomic` (weapons)?
8778 A lot of people, myself included, like to experiment with `std::memory_order`, but it is perhaps best to keep a close watch on those things in production code.
8779 Even vendors mess this up: Microsoft had to fix their `shared_ptr` (weak refcount decrement wasn't synchronized-with the destructor, if I recall correctly, although it was only a problem on ARM, not Intel)
8780 and everyone (gcc, clang, Microsoft, and intel) had to fix their `compare_exchange_*` this year, after an implementation bug caused losses to some finance company and they were kind enough to let the community know.
8782 It should definitely mention that `volatile` does not provide atomicity, does not synchronize between threads, and does not prevent instruction reordering (neither compiler nor hardware), and simply has nothing to do with concurrency.
8784 if (source->pool != YARROW_FAST_POOL && source->pool != YARROW_SLOW_POOL) {
8785 THROW(YARROW_BAD_SOURCE);
8788 ??? 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?
8790 ???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")
8792 ## <a name="SScp-par"></a> CP.par: Parallelism
8796 Parallelism rule summary:
8801 ## <a name="SScp-simd"></a> CP.simd: SIMD
8810 ## <a name="SScp-free"></a> CP.free: Lock-free programming
8814 Lock-free programming rule summary:
8819 ### <a name="Rconc"></a> Don't use lock-free programming unless you absolutely have to
8823 It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures.
8825 **Alternative**: Use lock-free data structures implemented by others as part of some library.
8827 # <a name="S-errors"></a> E: Error handling
8829 Error handling involves:
8831 * Detecting an error
8832 * Transmitting information about an error to some handler code
8833 * Preserve the state of a program in a valid state
8834 * Avoid resource leaks
8836 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.
8838 The rules are designed to help avoid several kinds of errors:
8840 * Type violations (e.g., misuse of `union`s and casts)
8841 * Resource leaks (including memory leaks)
8843 * Lifetime errors (e.g., accessing an object after is has been `delete`d)
8844 * Complexity errors (logical errors make likely by overly complex expression of ideas)
8845 * Interface errors (e.g., an unexpected value is passed through an interface)
8847 Error-handling rule summary:
8849 * [E.1: Develop an error-handling strategy early in a design](#Re-design)
8850 * [E.2: Throw an exception to signal that a function can't perform its assigned task](#Re-throw)
8851 * [E.3: Use exceptions for error handling only](#Re-errors)
8852 * [E.4: Design your error-handling strategy around invariants](#Re-design-invariants)
8853 * [E.5: Let a constructor establish an invariant, and throw if it cannot](#Re-invariant)
8854 * [E.6: Use RAII to prevent leaks](#Re-raii)
8855 * [E.7: State your preconditions](#Re-precondition)
8856 * [E.8: State your postconditions](#Re-postcondition)
8858 * [E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable](#Re-noexcept)
8859 * [E.13: Never throw while being the direct owner of an object](#Re-never-throw)
8860 * [E.14: Use purpose-designed user-defined types as exceptions (not built-in types)](#Re-exception-types)
8861 * [E.15: Catch exceptions from a hierarchy by reference](#Re-exception-ref)
8862 * [E.16: Destructors, deallocation, and `swap` must never fail](#Re-never-fail)
8863 * [E.17: Don't try to catch every exception in every function](#Re-not-always)
8864 * [E.18: Minimize the use of explicit `try`/`catch`](#Re-catch)
8865 * [E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available](#Re-finally)
8867 * [E.25: ??? What to do in programs where exceptions cannot be thrown](#Re-no-throw)
8870 ### <a name="Re-design"></a> E.1: Develop an error-handling strategy early in a design
8874 A consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system.
8876 ### <a name="Re-throw"></a> E.2: Throw an exception to signal that a function can't perform its assigned task
8880 To make error handling systematic, robust, and non-repetitive.
8892 Foo bar { {Thing{1}, Thing{2}, Thing{monkey}}, {"my_file", "r"}, "Here we go!"};
8896 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.
8897 In each case, they throw an exception for `use()`'s caller to handle.
8898 If `use()` could handle the failure to construct `bar` it can take control using `try`/`catch`.
8899 In either case, `Foo`'s constructor correctly destroys constructed members before passing control to whatever tried to create a `Foo`.
8900 Note that there is no return value that could contain an error code.
8902 The `File_handle` constructor might defined like this:
8904 File_handle::File_handle(const string& name, const string& mode)
8905 :f{fopen(name.c_str(), mode.c_str())}
8908 throw runtime_error{"File_handle: could not open "S-+ name + " as " + mode"}
8913 It is often said that exceptions are meant to signal exceptional events and failures.
8914 However, that's a bit circular because "what is exceptional?"
8917 * A precondition that cannot be met
8918 * A constructor that cannot construct an object (failure to establish its class's [invariant](#Rc-struct))
8919 * An out-of-range error (e.g., `v[v.size()] =7`)
8920 * Inability to acquire a resource (e.g., the network is down)
8922 In contrast, termination of an ordinary loop is not exceptional.
8923 Unless the loop was meant to be infinite, termination is normal and expected.
8927 Don't use a `throw` as simply an alternative way of returning a value from a function.
8929 **Exception**: 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`.
8931 **See also**: [RAII](#Re-raii)
8933 **See also**: [discussion](#Sd-noexcept)
8935 ### <a name="Re-errors"></a> E.3: Use exceptions for error handling only
8939 To keep error handling separated from "ordinary code."
8940 C++ implementations tend to be optimized based on the assumption that exceptions are rare.
8942 ##### Example, don't
8944 int find_index(vector<string>& vec, const string& x) // don't: exception not used for error handling
8947 for (int i =0; i < vec.size(); ++i)
8948 if (vec[i] == x) throw i; // found x
8952 return -1; // not found
8955 This is more complicated and most likely runs much slower than the obvious alternative.
8956 There is nothing exceptional about finding a value in a `vector`.
8958 ### <a name="Re-design-invariants"></a> E.4: Design your error-handling strategy around invariants
8962 To use an objects 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.
8966 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.
8968 ### <a name="Re-invariant"></a> E.5: Let a constructor establish an invariant, and throw if it cannot
8972 Leaving an object without its invariant established is asking for trouble.
8973 Not all member function can be called.
8979 **See also**: [If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
8985 ### <a name="Re-raii"></a> E.6: Use RAII to prevent leaks
8989 Leaks are typically unacceptable. RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks.
8993 void f1(int i) // Bad: possibly leak
8995 int* p = new int[12];
8997 if (i < 17) throw Bad {"in f()", i};
9001 We could carefully release the resource before the throw:
9003 void f2(int i) // Clumsy: explicit release
9005 int* p = new int[12];
9009 throw Bad {"in f()", i};
9014 This is verbose. In larger code with multiple possible `throw`s explicit releases become repetitive and error-prone.
9016 void f3(int i) // OK: resource management done by a handle
9018 auto p = make_unique<int[12]>();
9020 if (i < 17) throw Bad {"in f()", i};
9024 Note that this works even when the `throw` is implicit because it happened in a called function:
9026 void f4(int i) // OK: resource management done by a handle
9028 auto p = make_unique<int[12]>();
9030 helper(i); // may throw
9034 Unless you really need pointer semantics, use a local resource object:
9036 void f5(int i) // OK: resource management done by local object
9040 helper(i); // may throw
9046 If there is no obvious resource handle, cleanup actions can be represented by a [`final_action` object](#Re-finally)
9050 But what do we do if we are writing a program where exceptions cannot be used?
9051 First challenge that assumption; there are many anti-exceptions myths around.
9052 We know of only a few good reasons:
9054 * We are on a system so small that the exception support would eat up most of our 2K or memory.
9055 * We are in a hard-real-time system and we don't have tools that allows us that an exception is handled within the required time.
9056 * We are in a system with tons of legacy code using lots of pointers in difficult-to-understand ways
9057 (in particular without a recognizable ownership strategy) so that exceptions could cause leaks.
9058 * We get fired if we challenge our manager's ancient wisdom.
9060 Only the first of these reasons is fundamental, so whenever possible, use exception to implement RAII.
9061 When exceptions cannot be used, simulate RAII.
9062 That is, systematically check that objects are valid after construction and still release all resources in the destructor.
9063 One strategy is to add a `valid()` operation to every resource handle:
9067 vector<string> vs(100); // not std::vector: valid() added
9069 // handle error or exit
9072 Ifstream fs("foo"); // not std::ifstream: valid() added
9074 // handle error or exit
9078 } // destructors clean up as usual
9080 Obviously, this increases the size of the code, doesn't allow for implicit propagation of "exceptions" (`valid()` checks), and `valid()` checks can be forgotten.
9081 Prefer to use exceptions.
9083 **See also**: [discussion](#Sd-noexcept).
9089 ### <a name="Re-precondition"></a> E.7: State your preconditions
9093 To avoid interface errors.
9095 **See also**: [precondition rule](#Ri-pre).
9097 ### <a name="Re-postcondition"></a> E.8: State your postconditions
9101 To avoid interface errors.
9103 **See also**: [postcondition rule](#Ri-post).
9105 ### <a name="Re-noexcept"></a> E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable
9109 To make error handling systematic, robust, and efficient.
9113 double compute(double d) noexcept
9115 return log(sqrt(d <= 0 ? 1 : d));
9118 Here, I know that `compute` will not throw because it is composed out of operations that don't throw. By declaring `compute` to be `noexcept` I give the compiler and human readers information that can make it easier for them to understand and manipulate `compute`.
9122 Many standard library functions are `noexcept` including all the standard library functions "inherited" from the C standard library.
9126 vector<double> munge(const vector<double>& v) noexcept
9128 vector<double> v2(v.size());
9129 // ... do something ...
9132 The `noexcept` here states that I am not willing or able to handle the situation where I cannot construct the local `vector`. That is, I consider memory exhaustion a serious design error (on line with hardware failures) so that I'm willing to crash the program if it happens.
9134 **See also**: [discussion](#Sd-noexcept).
9136 ### <a name="Re-never-throw"></a> E.13: Never throw while being the direct owner of an object
9140 That would be a leak.
9144 void leak(int x) // don't: may leak
9146 auto p = new int{7};
9147 if (x < 0) throw Get_me_out_of_here{} // may leak *p
9149 delete p; // we may never get here
9152 One way of avoiding such problems is to use resource handles consistently:
9156 auto p = make_unique<int>(7);
9157 if (x < 0) throw Get_me_out_of_here{}; // will delete *p if necessary
9159 // no need for delete p
9162 **See also**: ???resource rule ???
9164 ### <a name="Re-exception-types"></a> E.14: Use purpose-designed user-defined types as exceptions (not built-in types)
9168 A user-defined type is unlikely to clash with other people's exceptions.
9175 throw Moonphase_error{};
9186 catch(Bufferpool_exhausted) {
9191 ##### Example, don't
9193 void my_code() // Don't
9196 throw 7; // 7 means "moon in the 4th quarter"
9200 void your_code() // Don't
9207 catch(int i) { // i == 7 means "input buffer too small"
9214 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 class with other people's use of them.
9216 ##### Example, don't
9218 void my_code() // Don't
9221 throw runtime_error{"moon in the 4th quarter"};
9225 void your_code() // Don't
9232 catch(runtime_error) { // runtime_error means "input buffer too small"
9237 **See also**: [Discussion](#Sd-???)
9241 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.
9243 ### <a name="Re-exception-ref"></a> E.15: Catch exceptions from a hierarchy by reference
9255 catch (exception e) { // don't: may slice
9261 catch (exception& e) { /* ... */ }
9265 Flag by-value exceptions if their type are part of a hierarchy (could require whole-program analysis to be perfect).
9267 ### <a name="Re-never-fail"></a> E.16: Destructors, deallocation, and `swap` must never fail
9271 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.
9273 ##### Example, don't
9278 ~Connection() // Don't: very bad destructor
9280 if (cannot_disconnect()) throw I_give_up{information};
9287 Many have tried to write reliable code violating this rule for examples such as a network connection that "refuses to close". To the best of our knowledge nobody has found a general way of doing this though occasionally, for very specific examples, you can get away with setting some state for future cleanup. Every example, we have seen of this is error-prone, specialized, and usually buggy.
9291 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.
9295 Deallocation functions, including `operator delete`, must be `noexcept`. `swap` functions must be `noexcept`. Most destructors are implicitly `noexcept` by default. destructors, make them `noexcept`.
9299 Catch destructors, deallocation operations, and `swap`s that `throw`. Catch such operations that are not `noexcept`.
9301 **See also**: [discussion](#Sd-never-fail)
9303 ### <a name="Re-not-always"></a> E.17: Don't try to catch every exception in every function
9307 Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste.
9308 Let an exception propagate until it reaches a function that can handle it.
9309 Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii).
9311 ##### Example, don't
9319 throw; // propagate exception
9325 * Flag nested try-blocks.
9326 * Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high")
9328 ### <a name="Re-catch"></a> E.18: Minimize the use of explicit `try`/`catch`
9332 `try`/`catch` is verbose and non-trivial uses error-prone.
9342 ### <a name="Re-finally"></a> E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available
9346 `finally` is less verbose and harder to get wrong than `try`/`catch`.
9352 void* p = malloc(1, n);
9353 auto _ = finally([p] { free(p); });
9359 ### <a name="Re-no-throw"></a> E.25: ??? What to do in programs where exceptions cannot be thrown
9363 ??? mostly, you can afford exceptions and code gets simpler with exceptions ???
9364 **See also**: [Discussion](#Sd-???).
9366 # <a name="S-const"></a> Con: Constants and Immutability
9368 You can't have a race condition on a constant.
9369 it is easier to reason about a program when many of the objects cannot change their values.
9370 Interfaces that promises "no change" of objects passed as arguments greatly increase readability.
9372 Constant rule summary:
9374 * [Con.1: By default, make objects immutable](#Rconst-immutable)
9375 * [Con.2: By default, make member functions `const`](#Rconst-fct)
9376 * [Con.3: By default, pass pointers and references to `const`s](#Rconst-ref)
9377 * [Con.4: Use `const` to define objects with values that do not change after construction](#Rconst-const)
9378 * [Con.5: Use `constexpr` for values that can be computed at compile time](#Rconst-constexpr)
9380 ### <a name="Rconst-immutable"></a> Con.1: By default, make objects immutable
9384 Immutable objects are easier to reason about, so make object non-`const` only when there is a need to change their value.
9396 ### <a name="Rconst-fct"></a> Con.2: By default, make member functions `const`
9410 ### <a name="Rconst-ref"></a> Con.3: By default, pass pointers and references to `const`s
9424 ### <a name="Rconst-const"></a> Con.4: Use `const` to define objects with values that do not change after construction
9438 ### <a name="Rconst-constexpr"></a> Con.5: Use `constexpr` for values that can be computed at compile time
9452 # <a name="S-templates"></a> T: Templates and generic programming
9454 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
9455 In C++, generic programming is supported by the `template` language mechanisms.
9457 Arguments to generic functions are characterized by sets of requirements on the argument types and values involved.
9458 In C++, these requirements are expressed by compile-time predicates called concepts.
9460 Templates can also be used for meta-programming; that is, programs that compose code at compile time.
9462 Template use rule summary:
9464 * [T.1: Use templates to raise the level of abstraction of code](#Rt-raise)
9465 * [T.2: Use templates to express algorithms that apply to many argument types](#Rt-algo)
9466 * [T.3: Use templates to express containers and ranges](#Rt-cont)
9467 * [T.4: Use templates to express syntax tree manipulation](#Rt-expr)
9468 * [T.5: Combine generic and OO techniques to amplify their strengths, not their costs](#Rt-generic-oo)
9470 Concept use rule summary:
9472 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
9473 * [T.11: Whenever possible use standard concepts](#Rt-std)
9474 * [T.12: Prefer concept names over `auto` for local variables](#Rt-auto)
9475 * [T.13: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
9478 Concept definition rule summary:
9480 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
9481 * [T.21: Define concepts to define complete sets of operations](#Rt-complete)
9482 * [T.22: Specify axioms for concepts](#Rt-axiom)
9483 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
9484 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
9485 * [T.25: Avoid negating constraints](#Rt-not)
9486 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
9489 Template interface rule summary:
9491 * [T.40: Use function objects to pass operations to algorithms](#Rt-fo)
9492 * [T.41: Require complete sets of operations for a concept](#Rt-operations)
9493 * [T.42: Use template aliases to simplify notation and hide implementation details](#Rt-alias)
9494 * [T.43: Prefer `using` over `typedef` for defining aliases](#Rt-using)
9495 * [T.44: Use function templates to deduce class template argument types (where feasible)](#Rt-deduce)
9496 * [T.46: Require template arguments to be at least `Regular` or `SemiRegular`](#Rt-regular)
9497 * [T.47: Avoid highly visible unconstrained templates with common names](#Rt-visible)
9498 * [T.48: If your compiler does not support concepts, fake them with `enable_if`](#Rt-concept-def)
9499 * [T.49: Where possible, avoid type-erasure](#Rt-erasure)
9500 * [T.50: Avoid writing an unconstrained template in the same namespace as a type](#Rt-unconstrained-adl)
9502 Template definition rule summary:
9504 * [T.60: Minimize a template's context dependencies](#Rt-depend)
9505 * [T.61: Do not over-parameterize members (SCARY)](#Rt-scary)
9506 * [T.62: Place non-dependent template members in a non-templated base class](#Rt-nondependent)
9507 * [T.64: Use specialization to provide alternative implementations of class templates](#Rt-specialization)
9508 * [T.65: Use tag dispatch to provide alternative implementations of functions](#Rt-tag-dispatch)
9509 * [T.66: Use selection using `enable_if` to optionally define a function](#Rt-enable_if)
9510 * [T.67: Use specialization to provide alternative implementations for irregular types](#Rt-specialization2)
9511 * [T.68: Use `{}` rather than `()` within templates to avoid ambiguities](#Rt-cast)
9512 * [T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point](#Rt-customization)
9514 Template and hierarchy rule summary:
9516 * [T.80: Do not naively templatize a class hierarchy](#Rt-hier)
9517 * [T.81: Do not mix hierarchies and arrays](#Rt-array) // ??? somewhere in "hierarchies"
9518 * [T.82: Linearize a hierarchy when virtual functions are undesirable](#Rt-linear)
9519 * [T.83: Do not declare a member function template virtual](#Rt-virtual)
9520 * [T.84: Use a non-template core implementation to provide an ABI-stable interface](#Rt-abi)
9521 * [T.??: ????](#Rt-???)
9523 Variadic template rule summary:
9525 * [T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types](#Rt-variadic)
9526 * [T.101: ??? How to pass arguments to a variadic template ???](#Rt-variadic-pass)
9527 * [T.102: ??? How to process arguments to a variadic template ???](#Rt-variadic-process)
9528 * [T.103: Don't use variadic templates for homogeneous argument lists](#Rt-variadic-not)
9529 * [T.??: ????](#Rt-???)
9531 Metaprogramming rule summary:
9533 * [T.120: Use template metaprogramming only when you really need to](#Rt-metameta)
9534 * [T.121: Use template metaprogramming primarily to emulate concepts](#Rt-emulate)
9535 * [T.122: Use templates (usually template aliases) to compute types at compile time](#Rt-tmp)
9536 * [T.123: Use `constexpr` functions to compute values at compile time](#Rt-fct)
9537 * [T.124: Prefer to use standard-library TMP facilities](#Rt-std)
9538 * [T.125: If you need to go beyond the standard-library TMP facilities, use an existing library](#Rt-lib)
9539 * [T.??: ????](#Rt-???)
9541 Other template rules summary:
9543 * [T.140: Name all nontrivial operations](#Rt-name)
9544 * [T.141: Use an unnamed lambda if you need a simple function object in one place only](#Rt-lambda)
9545 * [T.142: Use template variables to simplify notation](#Rt-var)
9546 * [T.143: Don't write unintentionally nongeneric code](#Rt-nongeneric)
9547 * [T.144: Don't specialize function templates](#Rt-specialize-function)
9548 * [T.??: ????](#Rt-???)
9550 ## <a name="SS-GP"></a> T.gp: Generic programming
9552 Generic programming is programming using types and algorithms parameterized by types, values, and algorithms.
9554 ### <a name="Rt-raise"></a> T.1: Use templates to raise the level of abstraction of code
9558 Generality. Re-use. Efficiency. Encourages consistent definition of user types.
9562 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":
9564 template<typename T, typename A>
9565 // requires Incrementable<T>
9566 A sum1(vector<T>& v, A s)
9568 for (auto x : v) s+=x;
9572 template<typename T, typename A>
9573 // requires Simple_number<T>
9574 A sum2(vector<T>& v, A s)
9576 for (auto x : v) s = s + x;
9580 Assuming that `Incrementable` does not support `+` and `Simple_number` does not support `+=`, we have overconstrained implementers of `sum1` and `sum2`.
9581 And, in this case, missed an opportunity for a generalization.
9585 template<typename T, typename A>
9586 // requires Arithmetic<T>
9587 A sum(vector<T>& v, A s)
9589 for (auto x : v) s+=x;
9593 Assuming that `Arithmetic` requires both `+` and `+=`, we have constrained the user of `sum` to provide a complete arithmetic type.
9594 That is not a minimal requirement, but it gives the implementer of algorithms much needed freedom and ensures that any `Arithmetic` type
9595 can be user for a wide variety of algorithms.
9597 For additional generality and reusability, we could also use a more general `Container` or `Range` concept instead of committing to only one container, `vector`.
9601 If we define a template to require exactly the operations required for a single implementation of a single algorithm
9602 (e.g., requiring just `+=` rather than also `=` and `+`) and only those, we have overconstrained maintainers.
9603 We aim to minimize requirements on template arguments, but the absolutely minimal requirements of an implementation is rarely a meaningful concept.
9607 Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates)
9608 is to efficiently generalize operations/algorithms over a set of types with similar semantic properties.
9612 * Flag algorithms with "overly simple" requirements, such as direct use of specific operators without a concept.
9613 * Do not flag the definition of the "overly simple" concepts themselves; they may simply be building blocks for more useful concepts.
9615 ### <a name="Rt-algo"></a> T.2: Use templates to express algorithms that apply to many argument types
9619 Generality. Minimizing the amount of source code. Interoperability. Re-use.
9623 That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range:
9625 template<typename Iter, typename Val>
9626 // requires Input_iterator<Iter>
9627 // && Equality_comparable<Value_type<Iter>, Val>
9628 Iter find(Iter b, Iter e, Val v)
9635 Don't use a template unless you have a realistic need for more than one template argument type.
9640 ??? tough, probably needs a human
9642 ### <a name="Rt-cont"></a> T.3: Use templates to express containers and ranges
9646 Containers need an element type, and expressing that as a template argument is general, reusable, and type safe.
9647 It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it.
9651 template<typename T>
9652 // requires Regular<T>
9655 T* elem; // points to sz Ts
9659 vector<double> v(10);
9666 void* elem; // points to size elements of some type
9670 Container c(10, sizeof(double));
9671 ((double*)c.elem)[] = 9.9;
9673 This doesn't directly express the intent of the programmer and hides the structure of the program from the type system and optimizer.
9675 Hiding the `void*` behind macros simply obscures the problems and introduces new opportunities for confusion.
9677 **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.
9678 See [Stable base](#Rt-abi).
9682 * Flag uses of `void*`s and casts outside low-level implementation code
9684 ### <a name="Rt-expr"></a> T.4: Use templates to express syntax tree manipulation
9696 ### <a name="Rt-generic-oo"></a> T.5: Combine generic and OO techniques to amplify their strengths, not their costs
9700 Generic and OO techniques are complementary.
9704 Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces.
9707 // pure virtual functions
9712 class ConcreteCommand : public Command {
9713 // implement virtuals
9718 Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout. Examples include type erasure as with `std::shared_ptr`’s deleter. (But [don't overuse type erasure](#Rt-erasure).)
9722 In a class template, nonvirtual functions are only instantiated if they're used -- but virtual functions are instantiated every time. This can bloat code size, and may overconstrain a generic type by instantiating functionality that is never needed. Avoid this, even though the standard facets made this mistake.
9726 * Flag a class template that declares new (non-inherited) virtual functions.
9728 ## <a name="SS-concepts"></a> TPG.concepts: Concept rules
9730 Concepts is a facility for specifying requirements for template arguments.
9731 It is an [ISO technical specification](#Ref-conceptsTS), but not yet supported by currently shipping compilers.
9732 Concepts are, however, crucial in the thinking about generic programming and the basis of much work on future C++ libraries
9733 (standard and other).
9735 Concept use rule summary:
9737 * [T.10: Specify concepts for all template arguments](#Rt-concepts)
9738 * [T.11: Whenever possible use standard concepts](#Rt-std)
9739 * [T.14: Prefer concept names over `auto`](#Rt-auto)
9740 * [T.15: Prefer the shorthand notation for simple, single-type argument concepts](#Rt-shorthand)
9743 Concept definition rule summary:
9745 * [T.20: Avoid "concepts" without meaningful semantics](#Rt-low)
9746 * [T.21: Define concepts to define complete sets of operations](#Rt-complete)
9747 * [T.22: Specify axioms for concepts](#Rt-axiom)
9748 * [T.23: Differentiate a refined concept from its more general case by adding new use patterns](#Rt-refine)
9749 * [T.24: Use tag classes or traits to differentiate concepts that differ only in semantics](#Rt-tag)
9750 * [T.25: Avoid negating constraints](#Rt-not)
9751 * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use)
9754 ## <a name="SS-concept-use"></a> T.con-use: Concept use
9756 ### <a name="Rt-concepts"></a> T.10: Specify concepts for all template arguments
9760 Correctness and readability.
9761 The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template.
9762 A concept dramatically improves documentation and error handling for the template.
9763 Specifying concepts for template arguments is a powerful design tool.
9767 template<typename Iter, typename Val>
9768 requires Input_iterator<Iter>
9769 && Equality_comparable<Value_type<Iter>, Val>
9770 Iter find(Iter b, Iter e, Val v)
9775 or equivalently and more succinctly:
9777 template<Input_iterator Iter, typename Val>
9778 requires Equality_comparable<Value_type<Iter>, Val>
9779 Iter find(Iter b, Iter e, Val v)
9786 Until your compilers support the concepts language feature, leave the concepts in comments:
9788 template<typename Iter, typename Val>
9789 // requires Input_iterator<Iter>
9790 // && Equality_comparable<Value_type<Iter>, Val>
9791 Iter find(Iter b, Iter e, Val v)
9798 Plain `typename` (or `auto`) is the least constraining concept.
9799 It should be used only rarely when nothing more than "it's a type" can be assumed.
9800 This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking.
9802 **References**: TC++PL4, Palo Alto TR, Sutton
9806 Flag template type arguments without concepts
9808 ### <a name="Rt-std"></a> T.11: Whenever possible use standard concepts
9812 "Standard" concepts (as provided by the GSL, the ISO concepts TS, and hopefully soon the ISO standard itself)
9813 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.
9817 Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library.
9822 // don't define this: Sortable is in the GSL
9823 Ordered_container = Sequence<T> && Random_access<Iterator<T>> && Ordered<Value_type<T>>;
9825 void sort(Ordered_container& s);
9827 This `Ordered_container` is quite plausible, but it is very similar to the `Sortable` concept in the GSL (and the Range TS).
9828 Is it better? Is it right? Does it accurately reflect the standard's requirements for `sort`?
9829 It is better and simpler just to use `Sortable`:
9831 void sort(Sortable& s); // better
9835 The set of "standard" concepts is evolving as we approaches real (ISO) standardization.
9839 Designing a useful concept is challenging.
9845 * Look for unconstrained arguments, templates that use "unusual"/non-standard concepts, templates that use "homebrew" concepts without axioms.
9846 * Develop a concept-discovery tool (e.g., see [an early experiment](http://www.stroustrup.com/sle2010_webversion.pdf).
9848 ### <a name="Rt-auto"></a> T.12: Prefer concept names over `auto` for local variables
9852 `auto` is the weakest concept. Concept names convey more meaning than just `auto`.
9857 auto& x = v.front(); // bad
9858 String& s = v.begin(); // good
9864 ### <a name="Rt-shorthand"></a> T.13: Prefer the shorthand notation for simple, single-type argument concepts
9868 Readability. Direct expression of an idea.
9872 To say "`T` is `Sortable`":
9874 template<typename T> // Correct but verbose: "The parameter is
9875 requires Sortable<T> // of type T which is the name of a type
9876 void sort(T&); // that is Sortable"
9878 template<Sortable T> // Better: "The parameter is of type T
9879 void sort(T&); // which is Sortable"
9881 void sort(Sortable&); // Best: "The parameter is Sortable"
9883 The shorter versions better match the way we speak. Note that many templates don't need to use the `template` keyword.
9887 * Not feasible in the short term when people convert from the `<typename T>` and `<class T`> notation.
9888 * Later, flag declarations that first introduces a typename and then constrains it with a simple, single-type-argument concept.
9890 ## <a name="SS=concept-def"></a> T.con-def: Concept definition rules
9894 ### <a name="Rt-low"></a> T.20: Avoid "concepts" without meaningful semantics
9898 Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered."
9899 Simple constraints, such as "has a `+` operator" and "has a `>` operator" cannot be meaningfully specified in isolation
9900 and should be used only as building blocks for meaningful concepts, rather than in user code.
9904 template<typename T>
9905 concept Addable = has_plus<T>; // bad; insufficient
9907 template<Addable N> auto algo(const N& a, const N& b) // use two numbers
9915 auto z = plus(x, y); // z = 18
9919 auto zz = plus(xx, yy); // zz = "79"
9921 Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types.
9922 This `Addable` violates the mathematical rule that addition is supposed to be commutative: `a + b == b + a`.
9926 The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint.
9928 ##### Example (using TS concepts)
9930 template<typename T>
9931 // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
9932 concept Number = has_plus<T>
9937 template<Number N> auto algo(const N& a, const N& b) // use two numbers
9945 auto z = plus(x, y); // z = 18
9949 auto zz = plus(xx, yy); // error: string is not a Number
9953 Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept.
9957 * Flag single-operation `concepts` when used outside the definition of other `concepts`.
9958 * Flag uses of `enable_if` that appears to simulate single-operation `concepts`.
9960 ### <a name="Rt-complete"></a> T.21: Define concepts to define complete sets of operations
9964 Improves interoperability. Helps implementers and maintainers.
9968 template<typename T> Subtractable = requires(T a, T, b) { a-b; } // correct syntax?
9970 This makes no semantic sense. You need at least `+` to make `-` meaningful and useful.
9972 Examples of complete sets are
9974 * `Arithmetic`: `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`
9975 * `Comparable`: `<`, `>`, `<=`, `>=`, `==`, `!=`
9981 ### <a name="Rt-axiom"></a> T.22: Specify axioms for concepts
9985 A meaningful/useful concept has a semantic meaning.
9986 Expressing this semantics in a informal, semi-formal, or informal way makes the concept comprehensible to readers and the effort to express it can catch conceptual errors.
9987 Specifying semantics is a powerful design tool.
9991 template<typename T>
9992 // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules
9993 // axiom(T a, T b) { a + b == b + a; a - a == 0; a * (b + c) == a * b + a * c; /*...*/ }
9994 concept Number = requires(T a, T b) {
9995 {a + b} -> T; // the result of a + b is convertible to T
10003 This is an axiom in the mathematical sense: something that may be assumed without proof.
10004 In general, axioms are not provable, and when they are the proof is often beyond the capability of a compiler.
10005 An axiom may not be general, but the template writer may assume that it holds for all inputs actually used (similar to a precondition).
10009 In this context axioms are Boolean expressions.
10010 See the [Palo Alto TR](#S-references) for examples.
10011 Currently, C++ does not support axioms (even the ISO Concepts TS), so we have to make do with comments for a longish while.
10012 Once language support is available, the `//` in front of the axiom can be removed
10016 The GSL concepts have well defined semantics; see the Palo Alto TR and the Ranges TS.
10020 Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics.
10021 Finding good semantics can take effort and time.
10022 An incomplete set of constraints can still be very useful:
10024 ??? binary tree: rotate(), ...
10026 A "concept" that is incomplete or without a well-specified semantics can still be useful.
10027 However, it should not be assumed to be stable. Each new use case may require such an incomplete concepts to be improved.
10031 * Look for the word "axiom" in concept definition comments
10033 ### <a name="Rt-refine"></a> T.23: Differentiate a refined concept from its more general case by adding new use patterns.
10037 Otherwise they cannot be distinguished automatically by the compiler.
10041 template<typename I>
10042 concept bool Input_iterator = requires (I iter) { ++iter; };
10044 template<typename I>
10045 concept bool Fwd_iter = Input_iter<I> && requires (I iter) { iter++; }
10047 The compiler can determine refinement based on the sets of required operations.
10048 If two concepts have exactly the same requirements, they are logically equivalent (there is no refinement).
10050 This also decreases the burden on implementers of these types since
10051 they do not need any special declarations to "hook into the concept".
10055 * Flag a concept that has exactly the same requirements as another already-seen concept (neither is more refined). To disambiguate them, see [T.24](#Rt-tag).
10057 ### <a name="Rt-tag"></a> T.24: Use tag classes or traits to differentiate concepts that differ only in semantics.
10061 Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them.
10065 template<typename I> // iterator providing random access
10066 concept bool RA_iter = ...;
10068 template<typename I> // iterator providing random access to contiguous data
10069 concept bool Contiguous_iter =
10070 RA_iter<I> && is_contiguous<I>::value; // ??? why not is_contiguous<I>() or is_contiguous_v<I>?
10072 The programmer (in a library) must define `is_contiguous` (a trait) appropriately.
10076 Traits can be trains classes or type traits.
10077 These can be user-defined or standard-library ones.
10078 Prefer the standard-library ones.
10082 * The compiler flags ambiguous use of identical concepts.
10083 * Flag the definition of identical concepts.
10085 ### <a name="Rt-not"></a> T.25: Avoid negating constraints.
10089 Clarity. Maintainability.
10090 Functions with complementary requirements expressed using negation are brittle.
10094 Initially, people will try to define functions with complementary requirements:
10096 template<typename T>
10097 requires !C<T> // bad
10100 template<typename T>
10106 template<typename T> // general template
10109 template<typename T> // specialization by concept
10113 The compiler will choose the unconstrained template only when `C<T>` is
10114 unsatisfied. If you do not want to (or cannot) define an unconstrained
10115 version of `f()`, then delete it.
10117 template<typename T>
10120 The compiler will select the overload and emit an appropriate error.
10124 * Flag pairs of functions with `C<T>` and `!C<T>` constraints
10125 * Flag all constraint negation
10127 ### <a name="Rt-use"></a> T.27: Prefer to define concepts in terms of use-patterns rather than simple syntax
10131 The definition is more readable and corresponds directly to what a user has to write.
10132 Conversions are taken into account. You don't have to remember the names of all the type traits.
10142 ## <a name="SS-temp-interface"></a> Template interfaces
10146 ### <a name="Rt-fo"></a> T.40: Use function objects to pass operations to algorithms
10150 Function objects can carry more information through an interface than a "plain" pointer to function.
10151 In general, passing function objects give better performance than passing pointers to functions.
10155 bool greater(double x, double y) { return x>y; }
10156 sort(v, greater); // pointer to function: potentially slow
10157 sort(v, [](double x, double y) { return x>y; }); // function object
10158 sort(v, greater<>); // function object
10160 bool greater_than_7(double x) { return x>7; }
10161 auto x = find_if(v, greater_than_7); // pointer to function: inflexible
10162 auto y = find_if(v, [](double x) { return x>7; }); // function object: carries the needed data
10163 auto y = find_if(v, Greater_than<double>(7)); // function object: carries the needed data
10165 ??? these lambdas are crying out for auto parameters -- any objection to making the change?
10169 Lambdas generate function objects.
10173 The performance argument depends on compiler and optimizer technology.
10177 * Flag pointer to function template arguments.
10178 * Flag pointers to functions passed as arguments to a template (risk of false positives).
10180 ### <a name="Rt-operations"></a> T.41: Require complete sets of operations for a concept
10184 Ease of comprehension.
10185 Improved interoperability.
10186 Flexibility for template implementers.
10190 The issue here is whether to require the minimal set of operations for a template argument
10191 (e.g., `==` but not `!=` or `+` but not `+=`).
10192 The rule supports the view that a concept should reflect a (mathematically) coherent set of operations.
10202 ### <a name="Rt-alias"></a> T.42: Use template aliases to simplify notation and hide implementation details
10206 Improved readability. Implementation hiding. Note that template aliases replace many uses of traits to compute a type. They can also be used to wrap a trait.
10210 template<typename T, size_t N>
10213 using Iterator = typename std::vector<T>::iterator;
10217 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>::`.
10221 template<typename T>
10222 using Value_type<T> = container_traits<T>::value_type;
10224 This saves the user of `Value_type` from having to know the technique used to implement `value_type`s.
10228 * Flag use of `typename` as a disambiguator outside `using` declarations.
10231 ### <a name="Rt-using"></a> T.43: Prefer `using` over `typedef` for defining aliases
10235 Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration.
10236 Generality: `using` can be used for template aliases, whereas `typedef`s can't easily be templates.
10237 Uniformity: `using` is syntactically similar to `auto`.
10241 typedef int (*PFI)(int); // OK, but convoluted
10243 using PFI2 = int (*)(int); // OK, preferred
10245 template<typename T>
10246 typedef int (*PFT)(T); // error
10248 template<typename T>
10249 using PFT2 = int (*)(T); // OK
10253 * Flag uses of `typedef`. This will give a lot of "hits" :-(
10255 ### <a name="Rt-deduce"></a> T.44: Use function templates to deduce class template argument types (where feasible)
10259 Writing the template argument types explicitly can be tedious and unnecessarily verbose.
10263 tuple<int, string, double> t1 = {1, "Hamlet", 3.14}; // explicit type
10264 auto t2 = make_tuple(1, "Ophelia"s, 3.14); // better; deduced type
10266 Note the use of the `s` suffix to ensure that the string is a `std::string`, rather than a C-style string.
10270 Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions may become redundant in the future.
10274 Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly:
10276 vector<double> v = { 1, 2, 3, 7.9, 15.99 };
10281 Flag uses where an explicitly specialized type exactly matches the types of the arguments used.
10283 ### <a name="Rt-regular"></a> T.46: Require template arguments to be at least `Regular` or `SemiRegular`
10297 ### <a name="Rt-visible"></a> T.47: Avoid highly visible unconstrained templates with common names
10311 ### <a name="Rt-concept-def"></a> T.48: If your compiler does not support concepts, fake them with `enable_if`
10325 ### <a name="Rt-erasure"></a> T.49: Where possible, avoid type-erasure
10329 Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary.
10335 **Exceptions**: Type erasure is sometimes appropriate, such as for `std::function`.
10341 ### <a name="Rt-unconstrained-adl"></a> T.50: Avoid writing an unconstrained template in the same namespace as a type
10345 ADL will find the template even when you think it shouldn't.
10353 This rule should not be necessary; the committee cannot agree on how to fix ADL, but at least making it not consider unconstrained templates would solve many of the actual problems and remove the need for this rule.
10357 ??? 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`
10359 ## <a name="SS=temp-def"></a> TCP.def: Template definitions
10363 ### <a name="Rt-depend"></a> T.60: Minimize a template's context dependencies
10367 Eases understanding. Minimizes errors from unexpected dependencies. Eases tool creation.
10375 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. For example, an algorithm usually uses other algorithms.
10381 ### <a name="Rt-scary"></a> T.61: Do not over-parameterize members (SCARY)
10385 A member that does not depend on a template parameter cannot be used except for a specific template argument.
10386 This limits use and typically increases code size.
10390 template<typename T, typename A = std::allocator{}>
10391 // requires Regular<T> && Allocator<A>
10394 struct Link { // does not depend on A
10400 using iterator = Link*;
10402 iterator first() const { return head; }
10410 List<int, my_allocator> lst2;
10414 This looks innocent enough, but ???
10416 template<typename T>
10423 template<typename T, typename A = std::allocator{}>
10424 // requires Regular<T> && Allocator<A>
10428 using iterator = Link<T>*;
10430 iterator first() const { return head; }
10438 List<int, my_allocator> lst2;
10444 * Flag member types that do not depend on every template argument
10445 * Flag member functions that do not depend on every template argument
10447 ### <a name="Rt-nondependent"></a> T.62: Place non-dependent template members in a non-templated base class
10455 template<typename T>
10469 template<typename T>
10470 class Foo : public Foo_base {
10477 A more general version of this rule would be
10478 "If a template class member depends on only N template parameters out of M, place it in a base class with only N parameters."
10479 For N == 1, we have a choice of a base class of a class in the surrounding scope as in [T.41](#Rt-scary).
10481 ??? What about constants? class statics?
10487 ### <a name="Rt-specialization"></a> T.64: Use specialization to provide alternative implementations of class templates
10491 A template defines a general interface.
10492 Specialization offers a powerful mechanism for providing alternative implementations of that interface.
10496 ??? string specialization (==)
10498 ??? representation specialization ?
10508 ### <a name="Rt-tag-dispatch"></a> T.65: Use tag dispatch to provide alternative implementations of a function
10512 A template defines a general interface. ???
10516 ??? that's how we get algorithms like `std::copy` which compiles into a `memmove` call if appropriate for the arguments.
10520 When `concept`s become available such alternatives can be distinguished directly.
10526 ### <a name="Rt-enable_if"></a> T.66: Use selection using `enable_if` to optionally define a function
10540 ### <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
10544 To provide only intended flexibility, and avoid accidental environmental changes.
10546 If you intend to call your own helper function `helper(t)` with a value `t` that depends on a template type parameter, put it in a `::detail` namespace and qualify the call as `detail::helper(t);`. Otherwise the call becomes a customization point where any function `helper` in the namespace of `t`'s type can be invoked instead -- falling into the second option below, and resulting in problems like [unintentionally invoking unconstrained function templates of that name that happen to be in the same namespace as `t`'s type](#Rt-unconstrained-adl).
10548 There are three major ways to let calling code customize a template.
10550 * Call a member function. Callers can provide any type with such a named member function.
10555 t.f(); // require T to provide f()
10558 * Call a nonmember function without qualification. Callers can provide any type for which there is such a function available in the caller's context or in the namespace of the type.
10563 f(t); // require f(/*T*/) be available in caller's cope or in T's namespace
10566 * Invoke a "trait" -- usually a type alias to compute a type, or a `constexpr` function to compute a value, or in rarer cases a traditional traits template to be specialized on the user's type.
10571 test_traits<T>::f(t); // require customizing test_traits<> to get non-default functions/types
10572 test_traits<T>::value_type x;
10577 * 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.
10579 ## <a name="SS-temp-hier"></a> T.temp-hier: Template and hierarchy rules:
10581 Templates are the backbone of C++'s support for generic programming and class hierarchies the backbone of its support
10582 for object-oriented programming.
10583 The two language mechanisms can be use effectively in combination, but a few design pitfalls must be avoided.
10585 ### <a name="Rt-hier"></a> T.80: Do not naively templatize a class hierarchy
10589 Templatizing a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat.
10593 template<typename T>
10594 struct Container { // an interface
10595 virtual T* get(int i);
10596 virtual T* first();
10598 virtual void sort();
10601 template<typename T>
10602 class Vector : public Container<T> {
10610 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.
10612 Given this, the compiler cannot know if `vector<int>::sort()` is called, so it must generate code for it.
10613 Similar for `vector<string>::sort()`.
10614 Unless those two functions are called that's code bloat.
10615 Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations.
10619 In many cases you can provide a stable interface by not parameterizing a base; see [Rule](#Rt-abi).
10623 * Flag virtual functions that depend on a template argument. ??? False positives
10625 ### <a name="Rt-array"></a> T.81: Do not mix hierarchies and arrays
10629 An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.
10633 Assume that `Apple` and `Pear` are two kinds of `Fruit`s.
10635 void maul(Fruit* p)
10637 *p = Pear{}; // put a Pear into *p
10638 p[1] = Pear{}; // put a Pear into p[2]
10641 Apple aa [] = { an_apple, another_apple }; // aa contains Apples (obviously!)
10644 Apple& a0 = &aa[0]; // a Pear?
10645 Apple& a1 = &aa[1]; // a Pear?
10647 Probably, `aa[0]` will be a `Pear` (without the use af a cast!).
10648 If `sizeof(Apple) != sizeof(Pear)` the access to `aa[1]` will not be aligned to the proper start of an object in the array.
10649 We have a type violation and possibly (probably) a memory corruption.
10650 Never write such code.
10652 Note that `maul()` violates the a `T*` points to an individual object [Rule](#???).
10654 **Alternative**: Use a proper container:
10656 void maul2(Fruit* p)
10658 *p = Pear{}; // put a Pear into *p
10661 vector<Apple> va = { an_apple, another_apple }; // aa contains Apples (obviously!)
10663 maul2(aa); // error: cannot convert a vector<Apple> to a Fruit*
10664 maul2(&aa[0]); // you asked for it
10666 Apple& a0 = &aa[0]; // a Pear?
10668 Note that the assignment in `maul2()` violated the no-slicing [Rule](#???).
10672 * Detect this horror!
10674 ### <a name="Rt-linear"></a> T.82: Linearize a hierarchy when virtual functions are undesirable
10688 ### <a name="Rt-virtual"></a> T.83: Do not declare a member function template virtual
10692 C++ does not support that.
10693 If it did, vtbls could not be generated until link time.
10694 And in general, implementations must deal with dynamic linking.
10696 ##### Example, don't
10701 virtual bool intersect(T* p); // error: template cannot be virtual
10704 **Alternative**: ??? double dispatch, visitor, calculate which function to call
10708 The compiler handles that.
10710 ### <a name="Rt-abi"></a> T.84: Use a non-template core implementation to provide an ABI-stable interface
10714 Improve stability of code. Avoids code bloat.
10718 It could be a base class:
10720 struct Link_base { // stable
10725 template<typename T> // templated wrapper to add type safety
10726 struct Link : Link_base {
10731 Link_base* first; // first element (if any)
10732 int sz; // number of elements
10733 void add_front(Link_base* p);
10737 template<typename T>
10738 class List : List_base {
10740 void put_front(const T& e) { add_front(new Link<T>{e}); } // implicit cast to Link_base
10741 T& front() { static_cast<Link<T>*>(first).val; } // explicit cast back to Link<T>
10748 Now there is only one copy of the operations linking and unlinking elements of a `List`.
10749 The `Link` and `List` classes does nothing but type manipulation.
10751 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.
10753 **Alternative**: Use a [PIMPL](#???) implementation.
10759 ## <a name="SS-variadic"></a> T.var: Variadic template rules
10763 ### <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
10767 Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs.
10775 * Flag uses of `va_arg` in user code.
10777 ### <a name="Rt-variadic-pass"></a> T.101: ??? How to pass arguments to a variadic template ???
10785 ??? beware of move-only and reference arguments
10791 ### <a name="Rt-variadic-process"></a> T.102: How to process arguments to a variadic template
10799 ??? forwarding, type checking, references
10805 ### <a name="Rt-variadic-not"></a> T.103: Don't use variadic templates for homogeneous argument lists
10809 There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`.
10819 ## <a name="SS-meta"></a> T.meta: Template metaprogramming (TMP)
10821 Templates provide a general mechanism for compile-time programming.
10823 Metaprogramming is programming where at least one input or one result is a type.
10824 Templates offer Turing-complete (modulo memory capacity) duck typing at compile time.
10825 The syntax and techniques needed are pretty horrendous.
10827 ### <a name="Rt-metameta"></a> T.120: Use template metaprogramming only when you really need to
10831 Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain.
10832 However, there are real-world examples where template metaprogramming provides better performance that any alternative short of expert-level assembly code.
10833 Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code.
10834 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++.
10844 Instead, use concepts. But see [How to emulate concepts if you don't have language support](#Rt-emulate).
10850 **Alternative**: If the result is a value, rather than a type, use a [`constexpr` function](#Rt-fct).
10854 If you feel the need to hide your template metaprogramming in macros, you have probably gone too far.
10856 ### <a name="Rt-emulate"></a> T.121: Use template metaprogramming primarily to emulate concepts
10860 Until concepts become generally available, we need to emulate them using TMP.
10861 Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP.
10865 template<typename Iter>
10866 /*requires*/ enable_if<random_access_iterator<Iter>, void>
10867 advance(Iter p, int n) { p += n; }
10869 template<typename Iter>
10870 /*requires*/ enable_if<forward_iterator<Iter>, void>
10871 advance(Iter p, int n) { assert(n >= 0); while (n--) ++p;}
10875 Such code is much simpler using concepts:
10877 void advance(RandomAccessIterator p, int n) { p += n; }
10879 void advance(ForwardIterator p, int n) { assert(n >= 0); while (n--) ++p;}
10885 ### <a name="Rt-tmp"></a> T.122: Use templates (usually template aliases) to compute types at compile time
10889 Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time.
10893 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
10897 ??? big object / small object optimization
10903 ### <a name="Rt-fct"></a> T.123: Use `constexpr` functions to compute values at compile time
10907 A function is the most obvious and conventional way of expressing the computation of a value.
10908 Often a `constexpr` function implies less compile-time overhead than alternatives.
10912 "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values.
10916 template<typename T>
10917 // requires Number<T>
10918 constexpr T pow(T v, int n) // power/exponential
10921 while (n--) res *= v;
10925 constexpr auto f7 = pow(pi, 7);
10929 * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions.
10931 ### <a name="Rt-std"></a> T.124: Prefer to use standard-library TMP facilities
10935 Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known.
10945 ### <a name="Rt-lib"></a> T.125: If you need to go beyond the standard-library TMP facilities, use an existing library
10949 Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community.
10950 Write your own "advanced TMP support" only if you really have to.
10960 ## <a name="SS-temp-other"></a> Other template rules
10962 ### <a name="Rt-name"></a> T.140: Name all nontrivial operations
10966 Documentation, readability, opportunity for reuse.
10972 ##### Example, good
10978 whether functions, lambdas, or operators.
10982 * Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms.
10983 * Lambdas as [initializers](#???)
10989 ### <a name="Rt-lambda"></a> T.141: Use an unnamed lambda if you need a simple function object in one place only
10993 That makes the code concise and gives better locality than alternatives.
10997 ??? for-loop equivalent
10999 **Exception**: Naming a lambda can be useful for clarity even if it is used only once
11003 * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas).
11005 ### <a name="Rt-var"></a> T.142?: Use template variables to simplify notation
11009 Improved readability.
11019 ### <a name="Rt-nongeneric"></a> T.143: Don't write unintentionally nongeneric code
11023 Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available.
11027 Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering.
11029 for (auto i = first; i < last; ++i) { // less generic
11033 for (auto i = first; i != last; ++i) { // good; more generic
11037 Of course, range-for is better still where it does what you want.
11041 Use the least-derived class that has the functionality you need.
11049 class derived1 : public base {
11054 class derived2 : public base {
11059 void myfunc(derived& param) // bad, unless there is a specific reason for limiting to derived1 objects only
11065 void myfunc(base& param) // good, uses only base interface so only commit to that
11073 * Flag comparison of iterators using `<` instead of `!=`.
11074 * 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.
11075 * Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type.
11077 ### <a name="Rt-specialize-function"></a> T.144: Don't specialize function templates
11081 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.
11087 **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).
11091 * Flag all specializations of a function template. Overload instead.
11093 # <a name="S-cpl"></a> CPL: C-style programming
11095 C and C++ are closely related languages.
11096 They both originate in "Classic C" from 1978 and have evolved in ISO committees since then.
11097 Many attempts have been made to keep them compatible, but neither is a subset of the other.
11101 * [CPL.1: Prefer C++ to C](#Rcpl-C)
11102 * [CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++](#Rcpl-subset)
11103 * [CPL.3: If you must use C for interfaces, use C++ in the code using such interfaces](#Rcpl-interface)
11105 ### <a name="Rcpl-C"></a> CPL.1: Prefer C++ to C
11109 C++ provides better type checking and more notational support.
11110 It provides better support for high-level programming and often generates faster code.
11116 int* pi = pv; // not C++
11117 *pi = 999; // overwrite sizeof(int) bytes near &ch
11121 Use a C++ compiler.
11123 ### <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++
11127 That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C."
11131 int* p1 = malloc(10*sizeof(int)); // not C++
11132 int* p2 = static_cast<int*>(malloc(10*sizeof(int))); // not C, C-style C++
11133 int* p3 = new int[10]; // not C
11134 int* p4 = (int*)malloc(10*sizeof(int)); // both C and C++
11138 * Flag if using a build mode that compiles code as C.
11140 * The C++ compiler will enforce that the code is valid C++ unless you use C extension options.
11142 ### <a name="Rcpl-interface"></a> CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces
11146 C++ is more expressive than C and offer better support for many types of programming.
11150 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.
11151 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.
11155 You can call C from C++:
11158 double sqrt(double);
11161 extern "C" double sqrt(double);
11167 You can call C++ from C:
11170 X call_f(struct Y*, int);
11173 extern "C" X call_f(Y* p, int i)
11175 return p->f(i); // possibly a virtual function call
11182 # <a name="S-source"></a> SF: Source files
11184 Distinguish between declarations (used as interfaces) and definitions (used as implementations)
11185 Use header files to represent interfaces and to emphasize logical structure.
11187 Source file rule summary:
11189 * [SF.1: Use a `.cpp` suffix for code files and `.h` for interface files](#Rs-suffix)
11190 * [SF.2: A `.h` file may not contain object definitions or non-inline function definitions](#Rs-inline)
11191 * [SF.3: Use `.h` files for all declarations used in multiple sourcefiles](#Rs-suffix)
11192 * [SF.4: Include `.h` files before other declarations in a file](#Rs-include-order)
11193 * [SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface](#Rs-consistency)
11194 * [SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope](#Rs-using)
11195 * [SF.7: Don't put a `using`-directive in a header file](#Rs-using-directive)
11196 * [SF.8: Use `#include` guards for all `.h` files](#Rs-guards)
11197 * [SF.9: Avoid cyclic dependencies among source files](#Rs-cycles)
11199 * [SF.20: Use `namespace`s to express logical structure](#Rs-namespace)
11200 * [SF.21: Don't use an unnamed (anonymous) namespace in a header](#Rs-unnamed)
11201 * [SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities](#Rs-unnamed2)
11203 ### <a name="Rs-suffix"></a> SF.1: Use a `.cpp` suffix for code files and `.h` for interface files
11211 The specific names `.h` and `.cpp` are not required (but recommended) and other names are in widespread use.
11212 Examples are `.hh` and `.cxx`. Use such names equivalently.
11217 extern int a; // a declaration
11221 int a; // a definition
11222 void foo() { ++a; }
11224 `foo.h` provides the interface to `foo.cpp`. Global variables are best avoided.
11229 int a; // a definition
11230 void foo() { ++a; }
11232 `#include<foo.h>` twice in a program and you get a linker error for two one-definition-rule violations.
11236 * Flag non-conventional file names.
11237 * Check that `.h` and `.cpp` (and equivalents) follow the rules below.
11239 ### <a name="Rs-inline"></a> SF.2: A `.h` file may not contain object definitions or non-inline function definitions
11243 Including entities subject to the one-definition rule leads to linkage errors.
11249 **Alternative formulation**: A `.h` file must contain only:
11251 * `#include`s of other `.h` files (possibly with include guards
11253 * class definitions
11254 * function declarations
11255 * `extern` declarations
11256 * `inline` function definitions
11257 * `constexpr` definitions
11258 * `const` definitions
11259 * `using` alias definitions
11264 Check the positive list above.
11266 ### <a name="Rs-suffix"></a> SF.3: Use `.h` files for all declarations used in multiple sourcefiles
11270 Maintainability. Readability.
11275 void bar() { cout << "bar\n"; }
11279 void foo() { bar(); }
11281 A maintainer of `bar` cannot find all declarations of `bar` if its type needs changing.
11282 The user of `bar` cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker.
11286 * Flag declarations of entities in other source files not placed in a `.h`.
11288 ### <a name="Rs-include-order"></a> SF.4: Include `.h` files before other declarations in a file
11292 Minimize context dependencies and increase readability.
11297 #include<algorithm>
11300 // ... my code here ...
11306 // ... my code here ...
11308 #include<algorithm>
11313 This applies to both `.h` and `.cpp` files.
11315 **Exception**: Are there any in good code?
11321 ### <a name="Rs-consistency"></a> SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface
11325 This enables the compiler to do an early consistency check.
11331 int bar(long double);
11335 void foo(int) { /* ... */ }
11336 int bar(double) { /* ... */ }
11337 double foobar(int);
11339 The errors will not be caught until link time for a program calling `bar` or `foobar`.
11345 int bar(long double);
11351 void foo(int) { /* ... */ }
11352 int bar(double) { /* ... */ }
11353 double foobar(int); // error: wrong return type
11355 The return-type error for `foobar` is now caught immediately when `foo.cpp` is compiled.
11356 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.
11362 ### <a name="Rs-using"></a> SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope
11376 ### <a name="Rs-using-directive"></a> SF.7: Don't put a `using`-directive in a header file
11380 Doing so takes away an `#include`r's ability to effectively disambiguate and to use alternatives.
11390 ### <a name="Rs-guards"></a> SF.8: Use `#include` guards for all `.h` files
11394 To avoid files being `#include`d several times.
11401 // ... declarations ...
11406 Flag `.h` files without `#include` guards.
11408 ### <a name="Rs-cycles"></a> SF.9: Avoid cyclic dependencies among source files
11412 Cycles complicates comprehension and slows down compilation.
11413 Complicates conversion to use language-supported modules (when they become available).
11417 Eliminate cycles; don't just break them with `#include` guards.
11434 ### <a name="Rs-namespace"></a> SF.20: Use `namespace`s to express logical structure
11448 ### <a name="Rs-unnamed"></a> SF.21: Don't use an unnamed (anonymous) namespace in a header
11452 It is almost always a bug to mention an unnamed namespace in a header file.
11460 * Flag any use of an anonymous namespace in a header file.
11462 ### <a name="Rs-unnamed2"></a> SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities
11466 nothing external can depend on an entity in a nested unnamed namespace.
11467 Consider putting every definition in an implementation source file should be in an unnamed namespace unless that is defining an "external/exported" entity.
11471 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.
11479 # <a name="S-stdlib"></a> SL: The Standard Library
11481 Using only the bare language, every task is tedious (in any language).
11482 Using a suitable library any task can be reasonably simple.
11484 Standard-library rule summary:
11486 * [SL.1: Use libraries wherever possible](#Rsl-lib)
11487 * [SL.2: Prefer the standard library to other libraries](#Rsl-sl)
11490 ### <a name="Rsl-lib"></a> SL.1: Use libraries wherever possible
11494 Save time. Don't re-invent the wheel.
11495 Don't replicate the work of others.
11496 Benefit from other people's work when they make improvements.
11497 Help other people when you make improvements.
11499 **References**: ???
11501 ### <a name="Rsl-sl"></a> SL.2: Prefer the standard library to other libraries
11505 More people know the standard library.
11506 It is more likely to be stable, well-maintained, and widely available than your own code or most other libraries.
11508 ## SL.con: Containers
11520 ### SL.???: Use character-level input only when you have to; *expr.low*.
11522 ### SL.???: When reading, always consider ill-formed input; *expr.low*.
11528 ## SL:c: The C standard library
11530 ### SL.???: C-style strings
11532 ### SL.???: printf/scanf
11534 # <a name"S-A"></a> A: Architectural Ideas
11536 This section contains ideas about ???
11538 ### <a name"Ra-stable"></a> A.1 Separate stable from less stable part of code
11542 ### <a name"Ra-reuse"></a> A.2 Express potentially reusable parts as a library
11546 ### <a name"Ra-lib"></a> A.3 Express potentially separately maintained parts as a library
11550 # <a name="S-not"></a> Non-Rules and myths
11552 This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend.
11553 In the context of the styles of programming we recommend and support with the guidelines, these "non-rules" would do harm.
11557 * all declarations on top of function
11558 * single-return rule
11560 * one class per source file
11561 * two-phase initialization
11564 # <a name="S-references"></a> RF: References
11566 Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++.
11569 * focus on lower-level issues, such as the spelling of identifiers
11570 * are written by C++ novices
11571 * see "stopping programmers from doing unusual things" as their primary aim
11572 * aim at portability across many compilers (some 10 years old)
11573 * are written to preserve decades old code bases
11574 * aims at a single application domain
11575 * are downright counterproductive
11576 * are ignored (must be ignored for programmers to get their work done well)
11578 A bad coding standard is worse than no coding standard.
11579 However an appropriate set of guidelines are much better than no standards: "Form is liberating."
11581 Why can't we just have a language that allows all we want and disallows all we don't want ("a perfect language")?
11582 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.
11583 Also, your needs change over time and a general-purpose language is needed to allow you to adapt.
11584 A language that is ideal for today would be overly restrictive tomorrow.
11586 Coding guidelines adapt the use of a language to specific needs.
11587 Thus, there cannot be a single coding style for everybody.
11588 We expect different organizations to provide additions, typically with more restrictions and firmer style rules.
11590 Reference sections:
11592 * [RF.rules: Coding rules](#SS-rules)
11593 * [RF.books: Books with coding guidelines](#SS-books)
11594 * [RF.C++: C++ Programming (C++11/C++14)](#SS-C++)
11595 * [RF.web: Websites](#SS-web)
11596 * [RS.video: Videos about "modern C++"](#SS-vid)
11597 * [RF.man: Manuals](#SS-man)
11599 ## <a name="SS-rules"></a> RF.rules: Coding rules
11601 * [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html).
11603 * [Bloomberg: BDE C++ Coding](https://github.com/bloomberg/bde/wiki/CodingStandards.pdf).
11604 Has a strong emphasis on code organization and layout.
11606 * [GCC Coding Conventions](https://gcc.gnu.org/codingconventions.html).
11607 C++03 and (reasonably) a bit backwards looking.
11608 * [Google C++ Style Guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.html).
11609 Too timid and reflects its 1990s origins.
11610 [A critique from 2014](https://www.linkedin.com/pulse/20140503193653-3046051-why-google-style-guide-for-c-is-a-deal-breaker).
11611 Google are busy updating their code base and we don't know how accurately the posted guideline reflects their actual code.
11612 This set of recommendations is evolving.
11613 * [JSF++: JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS](http://www.stroustrup.com/JSF-AV-rules.pdf).
11614 Document Number 2RDU00001 Rev C. December 2005.
11615 For flight control software.
11616 For hard real time.
11617 This means that it is necessarily very restrictive ("if the program fails somebody dies").
11618 For example, no free store allocation or deallocation may occur after the plane takes off (no memory overflow and no fragmentation allowed).
11619 No exception may be used (because there was no available tool for guaranteeing that an exception would be handled within a fixed short time).
11620 Libraries used have to have been approved for mission critical applications.
11621 Any similarities to this set of guidelines are unsurprising because Bjarne Stroustrup was an author of JSF++.
11622 Recommended, but note its very specific focus.
11623 * [Mozilla Portability Guide](https://developer.mozilla.org/en-US/docs/Mozilla/C%2B%2B_Portability_Guide).
11624 As the name indicate, this aims for portability across many (old) compilers.
11625 As such, it is restrictive.
11626 * [Geosoft.no: C++ Programming Style Guidelines](http://geosoft.no/development/cppstyle.html).
11628 * [Possibility.com: C++ Coding Standard](http://www.possibility.com/Cpp/CppCodingStandard.html).
11630 * [SEI CERT: Secure C++ Coding Standard](https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637).
11631 A very nicely done set of rules (with examples and rationales) done for security-sensitive code.
11632 Many of their rules apply generally.
11633 * [High Integrity C++ Coding Standard](http://www.codingstandard.com/).
11634 * [llvm](http://llvm.org/docs/CodingStandards.html).
11635 Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain.
11638 ## <a name="SS-books"></a> RF.books: Books with coding guidelines
11640 * [Meyers14](#Meyers14) Scott Meyers: Effective Modern C++ (???). Addison-Wesley 2014. Beware of overly technical and overly definite rules.
11641 * [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. Recommended.
11642 * [Stroustrup05](#Stroustrup05) Bjarne Stroustrup: [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
11643 LCSD05. October 2005.
11644 * [Stroustrup14](#Stroustrup05) Stroustrup: [A Tour of C++](http://www.stroustrup.com/Tour.html).
11645 Addison Wesley 2014.
11646 Each chapter ends with an advice section consisting of a set of recommendations.
11647 * [Stroustrup13](#Stroustrup13) Stroustrup: [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html).
11648 Addison Wesley 2013.
11649 Each chapter ends with an advice section consisting of a set of recommendations.
11650 * Stroustrup: [Style Guide](http://www.stroustrup.com/Programming/PPP-style.pdf)
11651 for [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html).
11652 Mostly low-level naming and layout rules.
11653 Primarily a teaching tool.
11655 ## <a name="SS-C++"></a> RF.C++: C++ Programming (C++11/C++14)
11659 * Programming: Principles and Practice using C++
11661 ## <a name="SS-web"></a> RF.web: Websites
11663 * [isocpp.org](http://www.isocpp.com)
11664 * [Bjarne Stroustrup's home pages](http://www.stroustrup.com)
11665 * [WG21](http://www.open-std.org/jtc1/sc22/wg21/)
11666 * <a name="Boost"></a>
11667 [Boost](http://www.boost.org)
11668 * [Adobe open source](http://www.adobe.com/open-source.html)
11669 * [Poco libraries](http://pocoproject.org/)
11671 ## <a name="SS-vid"></a> RS.video: Videos about "modern C++"
11673 * Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012.
11674 * 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
11675 * All the talks from [CppCon '14](https://isocpp.org/blog/2014/11/cppcon-videos-c9)
11676 * Bjarne Stroustrup: [The essence of C++](https://www.youtube.com/watch?v=86xWVb4XIyE) at the University of Edinburgh. 2014.
11680 ## <a name="SS-man"></a> RF.man: Manuals
11682 * ISO C++ Standard C++11
11683 * ISO C++ Standard C++14
11684 * Palo Alto "Concepts" TR
11685 * ISO C++ Concepts TS
11686 * WG21 Ranges report
11688 ## <a name="SS-ack"></a> Acknowledgements
11690 Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.:
11697 * Zhuang, Jiangang (Jeff)
11700 # <a name="S-profile"></a> Profiles
11702 A "profile" is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee. "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be). "Portably enforceable" means they are like language rules, so programmers can count on enforcement tools giving the same answer for the same code.
11704 Code written to be warning-free using such a language profile is considered to conform to the profile. Conforming code is considered to be safe by construction with regard to the safety properties targeted by that profile. Conforming code will not be the root cause of errors for that property, although such errors may be introduced into a program by other code, libraries or the external environment. A profile may also introduce additional library types to ease conformance and encourage correct code.
11708 * [Pro.type: Type safety](#SS-type)
11709 * [Pro.bounds: Bounds safety](#SS-bounds)
11710 * [Pro.lifetime: Lifetime safety](#SS-lifetime)
11712 ## <a name="SS-type"></a> Type safety profile
11714 This profile makes it easier to construct code that uses types correctly and avoids inadvertent type punning. It does so by focusing on removing the primary sources of type violations, including unsafe uses of casts and unions.
11716 For the purposes of this section, type-safety is defined to be the property that a program does not use a variable as a type it is not. Memory accessed as a type `T` should not be valid memory that actually contains an object of an unrelated type `U`. (Note that the safety is intended to be complete when combined also with [Bounds safety](#SS-bounds) and [Lifetime safety](#SS-lifetime).)
11718 The following are under consideration but not yet in the rules below, and may be better in other profiles:
11720 * narrowing arithmetic promotions/conversions (likely part of a separate safe-arithmetic profile)
11721 * arithmetic cast from negative floating point to unsigned integral type (ditto)
11722 * selected undefined behavior: ??? this is a big bucket, start with Gaby's UB list
11723 * selected unspecified behavior: ??? would this really be about safety, or more a portability concern?
11724 * constness violations? if we rely on it for safety
11726 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
11728 ### <a name="Pro-type-reinterpretcast"></a> Type.1: Don't use `reinterpret_cast`.
11732 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`.
11736 std::string s = "hello world";
11737 double* p = reinterpret_cast<double*>(&s); // BAD
11741 Issue a diagnostic for any use of `reinterpret_cast`. To fix: Consider using a `variant` instead.
11743 ### <a name="Pro-type-downcast"></a> Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead.
11747 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`.
11751 class base { public: virtual ~base() = 0; };
11753 class derived1 : public base { };
11755 class derived2 : public base {
11758 std::string get_s() { return s; }
11762 base* p = &d1; // ok, implicit conversion to pointer to base is fine
11764 derived2* p2 = static_cast<derived2*>(p); // BAD, tries to treat d1 as a derived2, which it is not
11765 cout << p2.get_s(); // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1
11769 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.
11771 ### <a name="Pro-type-constcast"></a> Type.3: Don't use `const_cast` to cast away `const` (i.e., at all).
11775 Casting away `const` is a lie. If the variable is actually declared `const`, it's a lie punishable by undefined behavior.
11779 void f(const int& i)
11781 const_cast<int&>(i) = 42; // BAD
11785 static const int j = 0;
11787 f(i); // silent side effect
11788 f(j); // undefined behavior
11790 **Exception**: 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.
11794 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`.
11796 ### <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`.
11800 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`.
11801 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.
11805 std::string s = "hello world";
11806 double* p = (double*)(&s); // BAD
11808 class base { public: virtual ~base() = 0; };
11810 class derived1 : public base { };
11812 class derived2 : public base {
11815 std::string get_s() { return s; }
11819 base* p = &d1; // ok, implicit conversion to pointer to base is fine
11821 derived2* p2 = (derived2*)(p); // BAD, tries to treat d1 as a derived2, which it is not
11822 cout << p2.get_s(); // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1
11824 void f(const int& i) {
11825 (int&)(i) = 42; // BAD
11829 static const int j = 0;
11831 f(i); // silent side effect
11832 f(j); // undefined behavior
11836 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.
11838 ### <a name="Pro-type-init"></a> Type.5: Don't use a variable before it has been initialized.
11840 [ES.20: Always initialize an object](#Res-always) is required.
11842 ### <a name="Pro-type-memberinit"></a> Type.6: Always initialize a member variable.
11846 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.
11850 struct X { int i; };
11853 use(x); // BAD, x hs not been initialized
11860 * 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.
11861 * Issue a diagnostic when constructing an object of a trivially constructible type without `()` or `{}` to initialize its members. To fix: Add `()` or `{}`.
11863 ### <a name="Pro-type-unions"></a> Type.7: Avoid accessing members of raw unions. Prefer `variant` instead.
11867 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.
11871 union U { int i; double d; };
11875 use(u.d); // BAD, undefined
11877 variant<int, double> u;
11878 u = 42; // u now contains int
11879 use(u.get<int>()); // ok
11880 use(u.get<double>()); // throws ??? update this when standardization finalizes the variant design
11882 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.
11886 * Issue a diagnostic for accessing a member of a union. To fix: Use a `variant` instead.
11888 ### <a name="Pro-type-varargs"></a> Type.8: Avoid reading from varargs or passing vararg arguments. Prefer variadic template parameters instead.
11892 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.
11899 result += va_arg(list, int); // BAD, assumes it will be passed ints
11904 sum(3.14159, 2.71828); // BAD, undefined
11906 template<class ...Args>
11907 auto sum(Args... args) { // GOOD, and much more flexible
11908 return (... + args); // note: C++17 "fold expression"
11911 sum(3, 2); // ok: 5
11912 sum(3.14159, 2.71828); // ok: ~5.85987
11914 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.
11918 * Issue a diagnostic for using `va_list`, `va_start`, or `va_arg`. To fix: Use a variadic template parameter list instead.
11919 * Issue a diagnostic for passing an argument to a vararg parameter. To fix: Use a different function, or `[[suppress(types)]]`.
11921 ## <a name="SS-bounds"></a> Bounds safety profile
11923 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.
11925 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.)
11927 The following are under consideration but not yet in the rules below, and may be better in other profiles:
11931 An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic.
11933 ### <a name="Pro-bounds-arithmetic"></a> Bounds.1: Don't use pointer arithmetic. Use `array_view` instead.
11937 Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. `array_view` is a bounds-checked, safe type for accessing arrays of data.
11941 void f(int* p, int count)
11943 if (count < 2) return;
11945 int* q = p + 1; // BAD
11949 d = (p - &n); // OK
11952 int n = *p++; // BAD
11954 if (count < 6) return;
11958 p[count - 1] = 2; // BAD
11960 use(&p[0], 3); // BAD
11963 ##### Example, good
11965 void f(array_view<int> a) // BETTER: use array_view in the function declaration
11967 if (a.length() < 2) return;
11969 int n = *a++; // OK
11971 array_view<int> q = a + 1; // OK
11973 if (a.length() < 6) return;
11977 a[count - 1] = 2; // OK
11979 use(a.data(), 3); // OK
11984 Issue a diagnostic for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
11986 ### <a name="Pro-bounds-arrayindex"></a> Bounds.2: Only index into arrays using constant expressions.
11990 Dynamic accesses into arrays are difficult for both tools and humans to validate as safe. `array_view` 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 an `array_view` constructed over the array.
11994 void f(array<int, 10> a, int pos)
11996 a[pos / 2] = 1; // BAD
11997 a[pos - 1] = 2; // BAD
11998 a[-1] = 3; // BAD - no replacement, just don't do this
11999 a[10] = 4; // BAD - no replacement, just don't do this
12002 ##### Example, good
12004 // ALTERNATIVE A: Use an array_view
12006 // A1: Change parameter type to use array_view
12007 void f(array_view<int, 10> a, int pos)
12009 a[pos / 2] = 1; // OK
12010 a[pos - 1] = 2; // OK
12013 // A2: Add local array_view and use that
12014 void f(array<int, 10> arr, int pos)
12016 array_view<int> a = {arr, pos}
12017 a[pos / 2] = 1; // OK
12018 a[pos - 1] = 2; // OK
12021 // ALTERNATIVE B: Use at() for access
12022 void f()(array<int, 10> a, int pos)
12024 at(a, pos / 2) = 1; // OK
12025 at(a, pos - 1) = 2; // OK
12033 for (int i = 0; i < COUNT; ++i)
12034 arr[i] = i; // BAD, cannot use non-constant indexer
12037 ##### Example, good
12039 // ALTERNATIVE A: Use an array_view
12043 array_view<int> av = arr;
12044 for (int i = 0; i < COUNT; ++i)
12048 // ALTERNATIVE B: Use at() for access
12052 for (int i = 0; i < COUNT; ++i)
12058 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.
12060 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.
12062 **Rewrite support**: Tooling can offer rewrites of array accesses that involve dynamic index expressions to use `at()` instead:
12066 void f(int i, int j)
12068 a[i + j] = 12; // BAD, could be rewritten as...
12069 at(a, i + j) = 12; // OK - bounds-checked
12072 ### <a name="Pro-bounds-decay"></a> Bounds.3: No array-to-pointer decay.
12076 Pointers should not be used as arrays. `array_view` is a bounds-checked, safe alternative to using pointers to access arrays.
12080 void g(int* p, size_t length);
12089 ##### Example, good
12091 void g(int* p, size_t length);
12092 void g1(array_view<int> av); // BETTER: get g() changed.
12099 g(a.data(), a.length()); // OK, if you have no choice
12100 g1(a); // OK - no decay here, instead use implicit array_view ctor
12105 Issue a diagnostic for any expression that would rely on implicit conversion of an array type to a pointer type.
12107 ### <a name="Pro-bounds-stdlib"></a> Bounds.4: Don't use standard library functions and types that are not bounds-checked.
12111 These functions all have bounds-safe overloads that take `array_view`. 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()`.
12117 array<int, 10> a, b;
12118 memset(a.data(), 0, 10); // BAD, and contains a length error
12119 memcmp(a.data(), b.data(), 10); // BAD, and contains a length error
12122 ##### Example, good
12126 array<int, 10> a, b;
12127 memset(a, 0); // OK
12128 memcmp({a, b}); // OK
12133 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.
12135 void f(std::vector<int>& v, std::array<int, 12> a, int i)
12137 v[0] = a[0]; // BAD
12138 v.at(0) = a[0]; // OK (alternative 1)
12139 at(v, 0) = a[0]; // OK (alternative 2)
12141 v.at(0) = a[i]; // BAD
12142 v.at(0) = a.at(i) // OK (alternative 1)
12143 v.at(0) = at(a, i); // OK (alternative 2)
12148 * Issue a diagnostic for any call to a standard library function that is not bounds-checked. ??? insert link to a list of banned functions
12152 * Impact on the standard library will require close coordination with WG21, if only to ensure compatibility even if never standardized.
12153 * We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like `memcmp` and shipping them in the GSL.
12154 * 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).
12156 ## <a name="SS-lifetime"></a> Lifetime safety profile
12158 # <a name="S-gsl"></a> GSL: Guideline support library
12160 The GSL is a small library of facilities designed to support this set of guidelines.
12161 Without these facilities, the guidelines would have to be far more restrictive on language details.
12163 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.
12165 The support library facilities are designed to be extremely lightweight (zero-overhead) so that they impose no overhead compared to using conventional alternatives.
12166 Where desirable, they can be "instrumented" with additional functionality (e.g., checks) for tasks such as debugging.
12168 These Guidelines assume a `variant` type, but this is not currently in GSL because the design is being actively refined in the standards committee.
12170 ## <a name="SS-views"></a> GSL.view: Views
12172 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.
12174 These "views" are never owners.
12176 References are never owners.
12178 The names are mostly ISO standard-library style (lower case and underscore):
12180 * `T*` // The `T*` is not an owner, may be null; assumed to be pointing to a single element.
12181 * `char*` // A C-style string (a zero-terminated array of characters); may be null.
12182 * `const char*` // A C-style string; may be null.
12183 * `T&` // The `T&` is not an owner and can never be a "null reference"; references are always bound to objects.
12185 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.
12186 Owners should be converted to resource handles (e.g., `unique_ptr` or `vector<T>`) or marked `owner<T*>`
12188 * `owner<T*>` // a `T*`that owns the object pointed/referred to; may be `nullptr`.
12189 * `owner<T&>` // a `T&` that owns the object pointed/referred to.
12191 `owner` is used to mark owning pointers in code that cannot be upgraded to use proper resource handles.
12192 Reasons for that include:
12194 * Cost of conversion.
12195 * The pointer is used with an ABI.
12196 * The pointer is part of the implementation of a resource handle.
12198 An `owner<T>` differs from a resource handle for a `T` by still requiring an explicit `delete`.
12200 An `owner<T>` is assumed to refer to an object on the free store (heap).
12202 If something is not supposed to be `nullptr`, say so:
12204 * `not_null<T>` // `T` is usually a pointer type (e.g., `not_null<int*>` and `not_null<owner<Foo*>>`) that may not be `nullptr`.
12205 `T` can be any type for which `==nullptr` is meaningful.
12207 * `array_view<T>` // [`p`:`p+n`), constructor from `{p, q}` and `{p, n}`; `T` is the pointer type
12208 * `array_view_p<T>` // `{p, predicate}` [`p`:`q`) where `q` is the first element for which `predicate(*p)` is true
12209 * `string_view` // `array_view<char>`
12210 * `cstring_view` // `array_view<const char>`
12212 A `*_view<T>` refers to zero or more mutable `T`s unless `T` is a `const` type.
12214 "Pointer arithmetic" is best done within `array_view`s.
12215 A `char*` that points to something that is not a C-style string (e.g., a pointer into an input buffer) should be represented by an `array_view`.
12216 There is no really good way to say "pointer to a single `char` (`string_view{p, 1}` can do that, and `T*` where `T` is a `char` in a template that has not been specialized for C-style strings).
12218 * `zstring` // a `char*` supposed to be a C-style string; that is, a zero-terminated sequence of `char` or `null_ptr`
12219 * `czstring` // a `const char*` supposed to be a C-style string; that is, a zero-terminated sequence of `const` `char` or `null_ptr`
12221 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.
12222 A sequence of characters that is not assumed to be zero-terminated should be a `char*`, rather than a `zstring`.
12223 French accent optional.
12225 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?
12227 ## <a name="SS-ownership"></a> GSL.owner: Ownership pointers
12229 * `unique_ptr<T>` // unique ownership: `std::unique_ptr<T>`
12230 * `shared_ptr<T>` // shared ownership: `std::shared_ptr<T>` (a counted pointer)
12231 * `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.
12232 * `dyn_array<T>` // ??? needed ??? A heap-allocated array. The number of elements are determined at construction and fixed thereafter.
12233 The elements are mutable unless `T` is a `const` type. Basically an `array_view` that allocates and owns its elements.
12235 ## <a name="SS-assertions"></a> GSL.assert: Assertions
12237 * `Expects` // precondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
12238 // `Expects(p)` terminates the program unless `p == true`
12239 // ??? `Expect` in under control of some options (enforcement, error message, alternatives to terminate)
12240 * `Ensures` // postcondition assertion. Currently placed in function bodies. Later, should be moved to declarations.
12242 ## <a name="SS-utilities"></a> GSL.util: Utilities
12244 * `finally` // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f`
12245 * `narrow_cast` // `narrow_cast<T>(x)` is `static_cast<T>(x)`
12246 * `narrow` // `narrow<T>(x)` is `static_cast<T>(x)` if `static_cast<T>(x) == x` or it throws `narrowing_error`
12247 * `implicit` // "Marker" to put on single-argument constructors to explicitly make them non-explicit
12248 (I don't know how to do that except with a macro: `#define implicit`).
12249 * `move_owner` // `p = move_owner(q)` means `p = q` but ???
12251 ## <a name="SS-concepts"></a> GSL.concept: Concepts
12253 These concepts (type predicates) are borrowed from Andrew Sutton's Origin library, the Range proposal, and the ISO WG21 Palo Alto TR.
12254 They are likely to be very similar to what will become part of the ISO C++ standard.
12255 The notation is that of the ISO WG21 Concepts TS (???ref???).
12261 * `Pointer` // A type with `*`, `->`, `==`, and default construction (default construction is assumed to set the singular "null" value) [see smartptrconcepts](#Rr-smartptrconcepts)
12262 * `Unique_ptr` // A type that matches `Pointer`, has move (not copy), and matches the Lifetime profile criteria for a `unique` owner type [see smartptrconcepts](#Rr-smartptrconcepts)
12263 * `Shared_ptr` // A type that matches `Pointer`, has copy, and matches the Lifetime profile criteria for a `shared` owner type [see smartptrconcepts](#Rr-smartptrconcepts)
12264 * `EqualityComparable` // ???Must we suffer CaMelcAse???
12274 * `RegularFunction`
12279 # <a name="S-naming"></a> NL: Naming and layout rules
12281 Consistent naming and layout are helpful. If for no other reason because it minimizes "my style is better than your style" arguments.
12282 However, there are many, many, different styles around and people are passionate about them (pro and con).
12283 Also, most real-world projects includes code from many sources, so standardizing on a single style for all code is often impossible.
12284 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.
12285 IDEs and tools can help (as well as hinder).
12287 Naming and layout rules:
12289 * [NL 1: Don't say in comments what can be clearly stated in code](#Rl-comments)
12290 * [NL.2: State intent in comments](#Rl-comments-intent)
12291 * [NL.3: Keep comments crisp](#Rl-comments-crisp)
12292 * [NL.4: Maintain a consistent indentation style](#Rl-indent)
12293 * [NL.5: Don't encode type information in names](#Rl-name-type)
12294 * [NL.7: Make the length of a name roughly proportional to the length of its scope](#Rl-name-length)
12295 * [NL.8: Use a consistent naming style](#Rl-name)
12296 * [NL 9: Use ALL_CAPS for macro names only](#Rl-all-caps)
12297 * [NL.10: Avoid CamelCase](#Rl-camel)
12298 * [NL.15: Use spaces sparingly](#Rl-space)
12299 * [NL.16: Use a conventional class member declaration order](#Rl-order)
12300 * [NL.17: Use K&R-derived layout](#Rl-knr)
12301 * [NL.18: Use C++-style declarator layout](#Rl-ptr)
12303 Most of these rules are aesthetic and programmers hold strong opinions.
12304 IDEs also tend to have defaults and a range of alternatives.These rules are suggested defaults to follow unless you have reasons not to.
12306 More specific and detailed rules are easier to enforce.
12308 ### <a name="Rl-comments"></a> NL.1: Don't say in comments what can be clearly stated in code
12312 Compilers do not read comments.
12313 Comments are less precise than code.
12314 Comments are not updated as consistently as code.
12318 auto x = m*v1 + vv; // multiply m with v1 and add the result to vv
12322 Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++.
12324 ### <a name="Rl-comments-intent"></a> NL.2: State intent in comments
12328 Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation.
12332 void stable_sort(Sortable& c)
12333 // sort c in the order determined by <, keep equal elements (as defined by ==) in their original relative order
12335 // ... quite a few lines of non-trivial code ...
12340 If the comment and the code disagrees, both are likely to be wrong.
12342 ### <a name="Rl-comments-crisp"></a> NL.3: Keep comments crisp
12346 Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file.
12352 ### <a name="Rl-indent"></a> NL.4: Maintain a consistent indentation style
12356 Readability. Avoidance of "silly mistakes."
12361 for (i = 0; i < max; ++i); // bug waiting to happen
12369 ### <a name="Rl-name-type"></a> NL.5 Don't encode type information in names
12371 **Rationale**: If names reflects type rather than functionality, it becomes hard to change the types used to provide that functionality.
12372 Names with types encoded are either verbose or cryptic.
12373 Hungarian notation is evil (at least in a strongly statically-typed language).
12381 Some styles distinguishes members from local variable, and/or from global variable.
12385 S(int m) :m_{abs(m)} { }
12392 Some styles distinguishes types from non-types.
12394 typename<typename T>
12395 class Hash_tbl { // maps string to T
12399 Hash_tbl<int> index;
12403 ### <a name="Rl-name-length"></a> NL.7: Make the length of a name roughly proportional to the length of its scope
12415 ### <a name="Rl-name"></a> NL.8: Use a consistent naming style
12417 **Rationale**: Consistence in naming and naming style increases readability.
12421 Where are many styles and when you use multiple libraries, you can't follow all their differences conventions.
12422 Choose a "house style", but leave "imported" libraries with their original style.
12426 ISO Standard, use lower case only and digits, separate words with underscores:
12432 Avoid double underscores `__`.
12436 [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf):
12437 ISO Standard, but with upper case used for your own types and concepts:
12445 CamelCase: capitalize each word in a multi-word identifier:
12452 Some conventions capitalize the first letter, some don't.
12456 Try to be consistent in your use of acronyms, lengths of identifiers:
12459 int mean_time_between_failor {12}; // make up your mind
12463 Would be possible except for the use of libraries with varying conventions.
12465 ### <a name="Rl-all-caps"></a> NL 9: Use ALL_CAPS for macro names only
12469 To avoid confusing macros from names that obeys scope and type rules.
12477 This rule applies to non-macro symbolic constants:
12479 enum bad { BAD, WORSE, HORRIBLE }; // BAD
12483 * Flag macros with lower-case letters
12484 * Flag ALL_CAPS non-macro names
12486 ### <a name="Rl-camel"></a> NL.10: Avoid CamelCase
12490 The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ standard library.
12491 If you prefer CamelCase, you have to choose among different flavors of camelCase.
12501 ### <a name="Rl-space"></a> NL.15: Use spaces sparingly
12505 Too much space makes the text larger and distracts.
12511 int main (int argc, char * argv [ ])
12520 int main(int argc, char* argv[])
12527 Some IDEs have their own opinions and adds distracting space.
12531 We value well-placed whitespace as a significant help for readability. Just don't overdo it.
12533 ### <a name="Rl-order"></a> NL.16: Use a conventional class member declaration order
12537 A conventional order of members improves readability.
12539 When declaring a class use the following order
12541 * types: classes, enums, and aliases (`using`)
12542 * constructors, assignments, destructor
12546 Used the `public` before `protected` before `private` order.
12548 Private types and functions can be placed with private data.
12556 Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.
12558 ### <a name="Rl-knr"></a> NL.17: Use K&R-derived layout
12562 This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes well).
12566 In the context of C++, this style is often called "Stroustrup".
12604 **Note** a space between `if` and `(`
12608 Use separate lines for each statement, the branches of an `if`, and the body of a `for`.
12612 The `{` for a `class` and a `struct` in *not* on a separate line, but the `{` for a function is.
12616 Capitalize the names of your user-defined types to distinguish them from standards-library types.
12620 Do not capitalize function names.
12624 If you want enforcement, use an IDE to reformat.
12626 ### <a name="Rl-ptr"></a> NL.18: Use C++-style declarator layout
12630 The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types.
12631 The use in expressions argument doesn't hold for references.
12635 T& operator[](size_t); // OK
12636 T &operator[](size_t); // just strange
12637 T & operator[](size_t); // undecided
12641 Impossible in the face of history.
12643 # <a name="S-faq"></a> FAQ: Answers to frequently asked questions
12645 This section covers answers to frequently asked questions about these guidelines.
12647 ### <a name="Faq-aims"></a> FAQ.1: What do these guidelines aim to achieve?
12649 See the top of this page. 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.
12651 ### <a name="Faq-announced"></a> FAQ.2: When and where was this work first announced?
12653 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).
12655 ### <a name="Faq-maintainers"></a> FAQ.3: Who are the authors and maintainers of these guidelines?
12657 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!"
12659 ### <a name="Faq-contribute"></a> FAQ.4: How can I contribute?
12661 See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help!
12663 ### <a name="Faq-maintainer"></a> FAQ.5: How can I become an editor/maintainer?
12665 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!
12667 ### <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?
12669 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.
12671 ### <a name="Faq-isocpp"></a> FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`?
12673 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.
12675 ### <a name="Faq-cpp98"></a> FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version?
12677 No. These guidelines are about how to best use Standard C++14 (and, if you have an implementation available, the Concepts Lite Technical Specification) and write code assuming you have a modern conforming compiler.
12679 ### <a name="Faq-language-extensions"></a> FAQ.9: Do these guidelines propose new language features?
12681 No. These guidelines are about how to best use Standard C++14 + the Concepts Lite Technical Specification, and they limit themselves to recommending only those features.
12683 ### <a name="Faq-gsl"></a> FAQ.50: What is the GSL (guideline support library)?
12685 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.
12687 ### <a name="Faq-msgsl"></a> FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL?
12689 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.
12691 ### <a name="Faq-gsl-implementation"></a> FAQ.52: Why not supply an actual GSL implementation in/with these guidelines?
12693 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.
12695 ### <a name="Faq-boost"></a> FAQ.53: Why weren’t the GSL types proposed through Boost?
12697 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.
12699 ### <a name="Faq-gsl-iso"></a> FAQ.54: Has the GSL (guideline support library) been approved by the ISO C++ standards committee?
12701 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.
12703 ### <a name="Faq-gsl-string-view"></a> FAQ.55: If you’re using the standard types where available, why is the GSL `string_view` different from the `string_view` in the Library Fundamentals 1 Technical Specification? Why not just use the committee-approved `string_view`?
12705 Because `string_view` is still undergoing standardization, and is in a state for public review input to improve it. Types that appear in Technical Specifications (TSes) are not yet part of the International Standard (IS), and one reason they are put in TSes first is to gain experience with the feature before they are cast in a final form to become part of the standard. Some of the GSL authors are contributing what we have learned about `string_view` in the process of developing these guidelines, and a discussion of the differences, as a paper for the next ISO meeting for consideration along with all the other similar papers for the committee to consider as it decides on the final form of this feature.
12707 ### <a name="Faq-gsl-owner"></a> FAQ.56: Is `owner` the same as the proposed `observer_ptr`?
12709 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.
12711 ### <a name="Faq-gsl-stack-array"></a> FAQ.57: Is `stack_array` the same as the standard `array`?
12713 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.
12715 ### <a name="Faq-gsl-dyn-array"></a> FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`?
12717 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.
12719 ### <a name="Faq-gsl-expects"></a> FAQ.59: Is `Expects` the same as `assert`?
12721 No. It is a placeholder for language support for contract preconditions.
12723 ### <a name="Faq-gsl-ensures"></a> FAQ.60: Is `Ensures` the same as `assert`?
12725 No. It is a placeholder for language support for contract postconditions.
12727 # <a name="S-libraries"></a> Appendix A: Libraries
12729 This section lists recommended libraries, and explicitly recommends a few.
12731 ??? Suitable for the general guide? I think not ???
12733 # <a name="S-modernizing"></a> Appendix B: Modernizing code
12735 Ideally, we follow all rules in all code.
12736 Realistically, we have to deal with a lot of old code:
12738 * application code written before the guidelines were formulated or known
12739 * libraries written to older/different standards
12740 * code that we just haven't gotten around to modernizing
12742 If we have a million lines of new code, the idea of "just changing it all at once" is typically unrealistic.
12743 Thus, we need a way of gradually modernizing a code base.
12745 Upgrading older code to modern style can be a daunting task.
12746 Often, the old code is both a mess (hard to understand) and working correctly (for the current range of uses).
12747 Typically, the original programmer is not around and test cases incomplete.
12748 The fact that the code is a mess dramatically increases to effort needed to make any change and the risk of introducing errors.
12749 Often messy, old code runs unnecessarily slowly because it requires outdated compilers and cannot take advantage of modern hardware.
12750 In many cases, programs support would be required for major upgrade efforts.
12752 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.
12753 Making code "look pretty" or "follow modern style" are not by themselves reasons for change.
12754 There are risks implied by every change and costs (including the cost of lost opportunities) implied by having an outdated code base.
12755 The cost reductions must outweigh the risks.
12759 There is no one approach to modernizing code.
12760 How best to do it depends on the code, the pressure for updates, the backgrounds of the developers, and the available tool.
12761 Here are some (very general) ideas:
12763 * The ideal is "just upgrade everything." That gives the most benefits for the shortest total time.
12764 In most circumstances, it is also impossible.
12765 * We could convert a code base module for module, but any rules that affects interfaces (especially ABIs), such as [use `array_view`](#SS-views), cannot be done on a per-module basis.
12766 * 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.
12767 * We could start by focusing on the interfaces, e.g., make sure that no resources are lost and no pointer is misused.
12768 This would be a set of changes across the whole code base, but would most likely have huge benefits.
12770 Whichever way you choose, please note that the most advantages come with the highest conformance to the guidelines.
12771 The guidelines are not a random set of unrelated rules where you can randomly pick and choose with an expectation of success.
12773 We would dearly love to hear about experience and about tools used.
12774 Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools.
12776 # <a name="S-discussion"></a> Appendix C: Discussion
12778 This section contains follow-up material on rules and sets of rules.
12779 In particular, here we present further rationale, longer examples, and discussions of alternatives.
12781 ### <a name="Sd-order"></a> Discussion: Define and initialize member variables in the order of member declaration
12783 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.
12786 string email, first, last;
12788 Employee(const char* firstName, const char* lastName);
12792 Employee::Employee(const char* firstName, const char* lastName)
12793 : first(firstName),
12795 // BAD: first and last not yet constructed
12796 email(first + "." + last + "@acme.com")
12799 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.
12801 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.
12805 [[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
12807 ### <a name="???"></a> Use of `=`, `{}`, and `()` as initializers
12811 ### <a name="Sd-factory"></a> Discussion: Use a factory function if you need "virtual behavior" during initialization
12813 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:
12815 * *Pass the buck:* Just document that user code must call the post-initialization function right after constructing an object.
12816 * *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.
12817 * *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).)
12818 * *Use a factory function:* This way, you can easily force a mandatory invocation of a post-constructor function.
12820 Here is an example of the last option:
12824 B() { /* ... */ f(); /*...*/ } // BAD: see Item 49.1
12826 virtual void f() = 0;
12834 virtual void PostInitialize() // called right after construction
12835 { /* ... */ f(); /*...*/ } // GOOD: virtual dispatch is safe
12837 virtual void f() = 0;
12840 static shared_ptr<T> Create() // interface for creating objects
12842 auto p = make_shared<T>();
12843 p->PostInitialize();
12848 class D : public B { /* "¦ */ }; // some derived class
12850 shared_ptr<D> p = D::Create<D>(); // creating a D object
12852 This design requires the following discipline:
12854 * Derived classes such as `D` must not expose a public constructor. Otherwise, `D`'s users could create `D` objects that don't invoke `PostInitialize`.
12855 * Allocation is limited to `operator new`. `B` can, however, override `new` (see Items 45 and 46).
12856 * `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.
12858 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.
12860 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).
12862 **References**: [[Alexandrescu01]](#Alexandrescu01) §3, [[Boost]](#Boost), [[Dewhurst03]](#Dewhurst03) §75, [[Meyers97]](#Meyers97) §46, [[Stroustrup00]](#Stroustrup00) §15.4.3, [[Taligent94]](#Taligent94)
12864 ### <a name="Sd-dtor"></a> Discussion: Make base class destructors public and virtual, or protected and nonvirtual
12866 Should destruction behave virtually? That is, should destruction through a pointer to a `base` class should 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.
12870 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>`:
12874 ~base(); // BAD, not virtual
12875 virtual ~base(); // GOOD
12879 class derived : public base { /*...*/ };
12882 shared_ptr<base> pb = make_shared<derived>();
12884 } // ~pb invokes correct destructor only when ~base is virtual
12886 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:
12890 virtual ~my_policy(); // BAD, public and virtual
12892 ~my_policy(); // GOOD
12896 template<class Policy>
12897 class customizable : Policy { /*...*/ }; // note: private inheritance
12901 This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles.
12903 For a base class `Base`, calling code might try to destroy derived objects through pointers to `Base`, such as when using a `shared_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.
12905 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:
12907 * Whether it should behave virtually or not.
12908 * Whether it should be publicly available to all callers using a pointer to Base or else be a hidden internal implementation detail.
12910 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.
12912 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.
12914 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.)
12916 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.
12920 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.
12922 Consider also this rare case:
12924 * `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.
12925 * 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.
12927 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.
12929 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`.
12931 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.
12933 **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
12935 ### <a name="Sd-noexcept"></a> Discussion: Usage of noexecpt
12939 ### <a name="Sd-never-fail"></a> Discussion: Destructors, deallocation, and swap must never fail
12941 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.
12947 nefarious() { /* code that could throw */ } // ok
12948 ~nefarious() { /* code that could throw */ } // BAD, should not throw
12952 1. `nefarious` objects are hard to use safely even as local variables:
12955 void test(string& s)
12957 nefarious n; // trouble brewing
12958 string copy = s; // copy the string
12959 } // destroy copy and then n
12961 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.
12963 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:
12966 class innocent_bystander {
12967 nefarious member; // oops, poisons the enclosing class's destructor
12971 void test(string& s)
12973 innocent_bystander i; // more trouble brewing
12974 string copy = s; // copy the string
12975 } // destroy copy and then i
12977 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`.
12979 3. You can't reliably create global or static `nefarious` objects either:
12982 static nefarious n; // oops, any destructor exception can't be caught
12984 4. You can't reliably create arrays of `nefarious`:
12989 std::array<nefarious, 10> arr; // this line can std::terminate(!)
12992 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.
12994 5. You can't use `Nefarious` objects in standard containers:
12997 std::vector<nefarious> vec(10); // this is line can std::terminate()
12999 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.
13003 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.
13005 Consider the following advice and requirements found in the C++ Standard:
13007 > 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)
13009 > 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)
13011 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.
13012 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`:
13014 T& T::operator=(const T& other) {
13019 (See also Item 56. ???)
13021 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).
13023 When using exceptions as your error handling mechanism, always document this behavior by declaring these functions `noexcept`. (See Item 75.)
13025 **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
13027 ## <a name="Sd-consistent"></a> Define Copy, move, and destroy consistently
13035 If you define a copy constructor, you must also define a copy assignment operator.
13039 If you define a move constructor, you must also define a move assignment operator.
13046 x(const x&) { /* stuff */ }
13048 // BAD: failed to also define a copy assignment operator
13050 x(x&&) { /* stuff */ }
13052 // BAD: failed to also define a move assignment operator
13057 x2 = x1; // pitfall: either fails to compile, or does something suspicious
13059 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.
13065 ~X() { /* custom stuff, such as closing hnd */ }
13066 // suspicious: no mention of copying or moving -- what happens to hnd?
13070 X x2 = x1; // pitfall: either fails to compile, or does something suspicious
13071 x2 = x1; // pitfall: either fails to compile, or does something suspicious
13073 If you define copying, and any base or member has a type that defines a move operation, you should also define a move operation.
13076 string s; // defines more efficient move operations
13077 // ... other data members ...
13079 x(const x&) { /* stuff */ }
13080 x& operator=(const x&) { /* stuff */ }
13082 // BAD: failed to also define a move construction and move assignment
13083 // (why wasn't the custom "stuff" repeated here?)
13090 return local; // pitfall: will be inefficient and/or do the wrong thing
13093 If you define any of the copy constructor, copy assignment operator, or destructor, you probably should define the others.
13097 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:
13099 * 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.)
13100 * 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.
13101 * 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.
13103 In many cases, holding properly encapsulated resources using RAII "owning" objects can eliminate the need to write these operations yourself. (See Item 13.)
13105 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.
13107 **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.
13108 In rare cases, classes that have members of strange types (such as reference members) are an exception because they have peculiar copy semantics.
13109 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.)
13111 **References**: [[C++CS]](#C++CS) Item 52; [[Cline99]](#Cline99) §30.01-14¸ [[Koenig97]](#Koenig97) §4¸ [[Stroustrup00]](#Stroustrup00) §5.5, §10.4¸ [[SuttHysl04b]](#SuttHysl04b)
13113 Resource management rule summary:
13115 * [Provide strong resource safety; that is, never leak anything that you think of as a resource](#Cr-safety)
13116 * [Never throw while holding a resource not owned by a handle](#Cr-never)
13117 * [A "raw" pointer or reference is never a resource handle](#Cr-raw)
13118 * [Never let a pointer outlive the object it points to](#Cr-outlive)
13119 * [Use templates to express containers (and other resource handles)](#Cr-templates)
13120 * [Return containers by value (relying on move or copy elision for efficiency)](#Cr-value-return)
13121 * [If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations](#Cr-handle)
13122 * [If a class is a container, give it an initializer-list constructor](#Cr-list)
13124 ### <a name="Cr-safety"></a> Provide strong resource safety; that is, never leak anything that you think of as a resource
13128 Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations.
13130 **Alternative formulation**: Have every resource represented as an object of some class managing its lifetime.
13138 T* elem; // sz elements on the free store, owned by the class object
13142 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.).
13146 ??? "odd" non-memory resource ???
13150 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 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.
13152 ### <a name="Cr-never"></a> Never throw while holding a resource not owned by a handle
13156 That would be a leak.
13162 FILE* f = fopen("a file", "r");
13163 ifstream is { "another file" };
13165 if (i == 0) return;
13170 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`:
13174 unique_ptr<FILE> f = fopen("a file", "r");
13176 if (i == 0) return;
13180 The code is simpler as well as correct.
13184 A checker must consider all "naked pointers" suspicious.
13185 A checker probably must rely on a human-provided list of resources.
13186 For starters, we know about the standard-library containers, `string`, and smart pointers.
13187 The use of `array_view` and `string_view` should help a lot (they are not resource handles).
13189 ### <a name="Cr-raw"></a> A "raw" pointer or reference is never a resource handle
13193 To be able to distinguish owners from views.
13197 This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr<T>` and `Range<T>` are not owners.
13199 ### <a name="Cr-outlive"></a> Never let a pointer outlive the object it points to
13203 To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system.
13207 string* bad() // really bad
13209 vector<string> v = { "this", "will", "cause" "trouble" };
13210 return &v[0]; // leaking a pointer into a destroyed member of a destroyed object (v)
13216 vector<int> xx = {7, 8, 9};
13217 string x = *p; // undefined behavior: x may not be 1
13218 *p = "Evil!"; // undefined behavior: we don't know what (if anything) is allocated a location p
13221 The `string`s of `v` are destroyed upon exit from `bad()` and so is `v` itself. This 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.
13225 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., `array_view` known not to be resource handles) to lower the number of cases to be examined. For starters, consider every class with a destructor a resource handle.
13227 ### <a name="Cr-templates"></a> Use templates to express containers (and other resource handles)
13231 To provide statically type-safe manipulation of elements.
13235 template<typename T> class Vector {
13237 T* elem; // point to sz elements of type T
13241 ### <a name="Cr-value-return"></a> Return containers by value (relying on move or copy elision for efficiency)
13245 To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime.
13249 vector<int> get_large_vector()
13254 auto v = get_large_vector(); // return by value is ok, most modern compilers will do copy elision
13262 Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`).
13264 ### <a name="Cr-handle"></a> If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations
13268 To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource.
13272 ??? Messing with pointers
13276 If all members are resource handles, rely on the default special operations where possible.
13278 template<typename T> struct Named {
13283 Now `Named` has a default constructor, a destructor, and efficient copy and move operations, provided `T` has.
13287 In general, a tool cannot know if a class is a resource handle. However, if a class has some of [the default operations](???), it should have all, and if a class has a member that is a resource handle, it should be considered a resource handle.
13289 ### <a name="Cr-list"></a> If a class is a container, give it an initializer-list constructor
13293 It is common to need an initial set of elements.
13297 template<typename T> class Vector {
13299 vector<std::initializer_list<T>>;
13303 Vector<string> vs = { "Nygaard", "Ritchie" };
13307 When is a class a container? ???
13309 # <a name="S-unclassified"></a> To-do: Unclassified proto-rules
13311 This is our to-do list.
13312 Eventually, the entries will become rules or parts of rules.
13313 Alternatively, we will decide that no change is needed and delete the entry.
13315 * No long-distance friendship
13316 * Should physical design (what's in a file) and large-scale design (libraries, groups of libraries) be addressed?
13318 * 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?
13319 * Should there be inline namespaces (a-la `std::literals::*_literals`)?
13320 * Avoid implicit conversions
13321 * Const member functions should be thread safe "¦ aka, but I don't really change the variable, just assign it a value the first time its called "¦ argh
13322 * Always initialize variables, use initialization lists for member variables.
13323 * Anyone writing a public interface which takes or returns void* should have their toes set on fire. That one has been a personal favourite of mine for a number of years. :)
13324 * Use `const`'ness wherever possible: member functions, variables and (yippee) const_iterators
13326 * `(size)` vs. `{initializers}` vs. `{Extent{size}}`
13327 * Don't overabstract
13328 * Never pass a pointer down the call stack
13329 * falling through a function bottom
13330 * 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?
13331 * Speaking of virtual functions, should non-virtual interface be promoted? NO. (public non-virtual foo() calling private/protected do_foo())? Not a new thing, seeing as locales/streams use it, but it seems to be under-emphasized.
13332 * 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?
13333 * Speaking of lambdas, what would weigh in on the decision between lambdas and (local?) classes in algorithm calls and other callback scenarios?
13334 * 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?
13335 * What to do with leaks out of temporaries? : `p = (s1 + s2).c_str();`
13336 * pointer/iterator invalidation leading to dangling pointers:
13340 int* p = new int[700];
13344 vector<int> v(700);
13348 // ... use q and q2 ...
13352 * private inheritance vs/and membership
13353 * avoid static class members variables (race conditions, almost-global variables)
13355 * Use RAII lock guards (`lock_guard`, `unique_lock`, `shared_lock`), never call `mutex.lock` and `mutex.unlock` directly (RAII)
13356 * Prefer non-recursive locks (often used to work around bad reasoning, overhead)
13357 * 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`?
13358 * If two or more mutexes must be acquired at the same time, use `std::lock` (or another deadlock avoidance algorithm?)
13359 * 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.
13360 * 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)
13361 * 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)
13362 * individual `shared_ptr` objects are not thread-safe: a thread cannot call a non-const member function of `shared_ptr` while another thread accesses (but different threads can call non-const member functions on copies of a `shared_ptr` that refer to the same shared object)
13364 * rules for arithmetic
13368 * <a name="Alexandrescu01"></a>
13369 \[Alexandrescu01\]: A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
13370 * <a name="C++03"></a>
13371 \[C++03\]: ISO/IEC 14882:2003(E), Programming LanguagesC++ (updated ISO and ANSI C++ Standard including the contents of (C++98) plus errata corrections).
13372 * <a name="C++CS"></a>
13374 * <a name="Cargill92"></a>
13375 \[Cargill92\]: T. Cargill. C++ Programming Style (Addison-Wesley, 1992).
13376 * <a name="Cline99"></a>
13377 \[Cline99\]: M. Cline, G. Lomow, and M. Girou. C++ FAQs (2ndEdition) (Addison-Wesley, 1999).
13378 * <a name="Dewhurst03"></a>
13379 \[Dewhurst03\]: S. Dewhurst. C++ Gotchas (Addison-Wesley, 2003).
13380 * <a name="Henricson97"></a>
13381 \[Henricson97\]: M. Henricson and E. Nyquist. Industrial Strength C++ (Prentice Hall, 1997).
13382 * <a name="Koenig97"></a>
13383 \[Koenig97\]: A. Koenig and B. Moo. Ruminations on C++ (Addison-Wesley, 1997).
13384 * <a name="Lakos96"></a>
13385 \[Lakos96\]: J. Lakos. Large-Scale C++ Software Design (Addison-Wesley, 1996).
13386 * <a name="Meyers96"></a>
13387 \[Meyers96\]: S. Meyers. More Effective C++ (Addison-Wesley, 1996).
13388 * <a name="Meyers97"></a>
13389 \[Meyers97\]: S. Meyers. Effective C++ (2ndEdition) (Addison-Wesley, 1997).
13390 * <a name="Meyers14"></a>
13391 \[Meyers14\]: S. Meyers. Effective Modern C++ (Addison-Wesley, 2014).
13392 * <a name="Murray93"></a>
13393 \[Murray93\]: R. Murray. C++ Strategies and Tactics (Addison-Wesley, 1993).
13394 * <a name="Stroustrup00"></a>
13395 \[Stroustrup00\]: B. Stroustrup. The C++ Programming Language (Special 3rdEdition) (Addison-Wesley, 2000).
13396 * <a name="Stroustrup05"></a>
13397 \[Stroustrup05\]: B. Stroustrup. [A rationale for semantically enhanced library languages](http://www.stroustrup.com/SELLrationale.pdf).
13398 * <a name="Stroustrup13"></a>
13399 \[Stroustrup13\]: B. Stroustrup. [The C++ Programming Language (4th Edition)](http://www.stroustrup.com/4th.html). Addison Wesley 2013.
13400 * <a name="Stroustrup14"></a>
13401 \[Stroustrup14\]: B. Stroustrup. [A Tour of C++](http://www.stroustrup.com/Tour.html).
13402 Addison Wesley 2014.
13403 * <a name="SuttHysl04b"></a>
13404 \[SuttHysl04b\]: H. Sutter and J. Hyslop. "Collecting Shared Objects" (C/C++ Users Journal, 22(8), August 2004).
13405 * <a name="SuttAlex05"></a>
13406 \[SuttAlex05\]: H. Sutter and A. Alexandrescu. C++ Coding Standards. Addison-Wesley 2005.
13407 * <a name="Sutter00"></a>
13408 \[Sutter00\]: H. Sutter. Exceptional C++ (Addison-Wesley, 2000).
13409 * <a name="Sutter02"></a>
13410 \[Sutter02\]: H. Sutter. More Exceptional C++ (Addison-Wesley, 2002).
13411 * <a name="Sutter04"></a>
13412 \[Sutter04\]: H. Sutter. Exceptional C++ Style (Addison-Wesley, 2004).
13413 * <a name="Taligent94"></a>
13414 \[Taligent94\]: Taligent's Guide to Designing Programs (Addison-Wesley, 1994).