From e4ea6c5374e1335bb16da55f3e23dd43308e461f Mon Sep 17 00:00:00 2001 From: Thibault Kruse Date: Wed, 30 Sep 2015 22:26:44 +0200 Subject: [PATCH] Replace **strong** fake headers with real markdown headers carrying section semantics --- CppCoreGuidelines.md | 4491 +++++++++++++++++++++++++++--------------- 1 file changed, 2917 insertions(+), 1574 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 945ec3e..27c6459 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -350,10 +350,12 @@ Without a philosophical basis the more concrete/specific/checkable rules lack ra ### P.1: Express ideas directly in code -**Reason**: Compilers don't read comments (or design documents) and neither do many programmers (consistently). +##### Reason + + Compilers don't read comments (or design documents) and neither do many programmers (consistently). What is expressed in code has a defined semantics and can (in principle) be checked by compilers and other tools. -**Example**: +##### Example class Date { // ... @@ -366,7 +368,7 @@ What is expressed in code has a defined semantics and can (in principle) be chec The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object. The second version leaves the reader guessing and opens more possibilities for uncaught bugs. -**Example**: +##### Example void do_something(vector& v) { @@ -400,7 +402,7 @@ A C++ programmer should know the basics of the standard library, and use it wher Any programmer should know the basics of the foundation libraries of the project being worked on, and use it appropriately. Any programmer using these guidelines should know the [Guidelines Support Library](#S-gsl), and use it appropriately. -**Example**: +##### Example change_speed(double s); // bad: what does s signify? // ... @@ -416,32 +418,42 @@ A better approach is to be explicit about the meaning of the double (new speed o We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone. If we wanted both absolute speed and deltas, we would have defined a `Delta` type. -**Enforcement**: very hard in general. +##### Enforcement + +very hard in general. * use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference) * flag uses of casts (casts neuter the type system) * detect code that mimics the standard library (hard) - ### P.2: Write in ISO Standard C++ -**Reason**: This is a set of guidelines for writing ISO Standard C++. +##### Reason -**Note**: There are environments where extensions are necessary, e.g., to access system resources. + This is a set of guidelines for writing ISO Standard C++. + +##### Note + +There are environments where extensions are necessary, e.g., to access system resources. In such cases, localize to use of necessary extensions and control their use with non-core Coding Guidelines. -**Note**: There are environments where restrictions on use of standard C++ language or library features are necessary, +##### Note + +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. In such cases, control their (dis)use with non-core Coding Guidelines. -**Enforcement**: Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions. +##### Enforcement +Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions. ### P.3: Express intent -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example int i = 0; while (i)` interfaces @@ -490,10 +510,11 @@ A programmer should be familiar with There is a huge scope for cleverness and semi-automated program transformation. - ### P.4: Ideally, a program should be statically type safe -**Reason**: Ideally, a program would be completely statically (compile-time) type safe. +##### Reason + + Ideally, a program would be completely statically (compile-time) type safe. Unfortunately, that is not possible. Problem areas: * unions @@ -502,10 +523,14 @@ Unfortunately, that is not possible. Problem areas: * range errors * narrowing conversions -**Note**: These areas are sources of serious problems (e.g., crashes and security violations). +##### Note + +These areas are sources of serious problems (e.g., crashes and security violations). We try to provide alternative techniques. -**Enforcement**: We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs. +##### Enforcement + +We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs. Always suggest an alternative. For example: @@ -515,12 +540,13 @@ For example: * range errors - use `array_view` * narrowing conversions - minimize their use and use `narrow` or `narrow_cast` where they are necessary - ### P.5: Prefer compile-time checking to run-time checking -**Reason**: Code clarity and performance. You don't need to write error handlers for errors caught at compile time. +##### Reason -**Example**: + Code clarity and performance. You don't need to write error handlers for errors caught at compile time. + +##### Example void initializer(Int x) // Int is an alias used for integers @@ -536,29 +562,32 @@ For example: // ... } -**Example; don't**: +##### Example don't void read(int* p, int n); // read max n integers into *p -**Example**: +##### Example void read(array_view r); // read into the range of integers r **Alternative formulation**: Don't postpone to run time what can be done well at compile time. -**Enforcement**: +##### Enforcement * look for pointer arguments * look for run-time checks for range violations. - ### P.6: What cannot be checked at compile time should be checkable at run time -**Reason**: Leaving hard-to-detect errors in a program is asking for crashes and bad results. +##### Reason -**Note**: 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). + Leaving hard-to-detect errors in a program is asking for crashes and bad results. -**Example, bad**: +##### Note + +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). + +##### Example, bad extern void f(int* p); // separately compiled, possibly dynamically loaded @@ -569,7 +598,9 @@ For example: 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. -**Example, bad**: We can of course pass the number of elements along with the pointer: +##### Example, bad + +We can of course pass the number of elements along with the pointer: extern void f2(int* p, int n); // separately compiled, possibly dynamically loaded @@ -582,7 +613,9 @@ Passing the number of elements as an argument is better (and far more common) th Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?). -**Example, bad**: The standard library resource management pointers fail to pass the size when they point to an object: +##### Example, bad + + The standard library resource management pointers fail to pass the size when they point to an object: extern void f3(unique_ptr, int n); // separately compiled, possibly dynamically loaded @@ -591,7 +624,9 @@ Also, it is implicit that `f2()` is supposed to `delete` its argument (or did th f3(make_unique(n), m); // bad: pass ownership and size separately } -**Example**: We need to pass the pointer and the number of elements as an integral object: +##### Example + +We need to pass the pointer and the number of elements as an integral object: extern void f4(vector&); // separately compiled, possibly dynamically loaded extern void f4(array_view); // separately compiled, possibly dynamically loaded @@ -605,7 +640,9 @@ Also, it is implicit that `f2()` is supposed to `delete` its argument (or did th 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. -**Example**: How do we transfer both ownership and all information needed for validating use? +##### Example + +How do we transfer both ownership and all information needed for validating use? vector f5(int n) // OK: move { @@ -628,23 +665,25 @@ This design carries the number of elements along as an integral part of an objec return p; } -**Example**: +##### Example * ??? * show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need? Or strings as "free-style" options -**Enforcement**: +##### Enforcement * Flag (pointer, count) interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons) * ??? ### P.7: Catch run-time errors early -**Reason**: Avoid "mysterious" crashes. +##### Reason + + Avoid "mysterious" crashes. Avoid errors leading to (possibly unrecognized) wrong results. -**Example**: +##### Example void increment1(int* p, int n) // bad: error prone { @@ -692,7 +731,9 @@ If all we had was a typo so that we meant to use `n` as the bound, the code coul // ... } -**Example, bad**: Don't repeatedly check the same value. Don't pass structured data as strings: +##### Example, bad + + Don't repeatedly check the same value. Don't pass structured data as strings: Date read_date(istream& is); // read date from istream @@ -714,7 +755,9 @@ If all we had was a typo so that we meant to use `n` as the bound, the code coul The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data). -**Example**: Excess checking can be costly. +##### Example + +Excess checking can be costly. 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. @@ -740,7 +783,7 @@ The physical law for a jet (`e*e < x*x + y*y + z*z`) is not an invariant because ??? -**Enforcement**: +##### Enforcement * Look at pointers and arrays: Do range-checking early * Look at conversions: eliminate or mark narrowing conversions. @@ -748,12 +791,13 @@ The physical law for a jet (`e*e < x*x + y*y + z*z`) is not an invariant because * Look for structured data (objects of classes with invariants) being converted into strings * ??? - ### P.8: Don't leak any resource -**Reason**: Essential for long-running programs. Efficiency. Ability to recover from errors. +##### Reason -**Example, bad**: + Essential for long-running programs. Efficiency. Ability to recover from errors. + +##### Example, bad void f(char* name) { @@ -776,7 +820,7 @@ Prefer [RAII](#Rr-raii): **See also**: [The resource management section](#S-resource) -**Enforcement**: +##### Enforcement * Look at pointers: classify them into non-owners (the default) and owners. Where feasible, replace owners with standard-library resource handles (as in the example above). @@ -784,14 +828,19 @@ Prefer [RAII](#Rr-raii): * Look for naked `new` and `delete` * Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`) - ### P.9: Don't waste time or space -**Reason**: This is C++. +##### Reason -**Note**: 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. + This is C++. -**Example**: ??? more and better suggestions for gratuitous waste welcome ??? +##### Note + +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. + +##### Example + +??? more and better suggestions for gratuitous waste welcome ??? struct X { char ch; @@ -831,14 +880,16 @@ The spurious definition of copy operations disables move semantics so that the r The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`. There are several more performance bugs and gratuitous complication. -**Note**: An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert. +##### Note + +An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert. However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like. 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. After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines. -**Enforcement**: Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste. - +##### Enforcement +Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste. # I: Interfaces @@ -877,9 +928,12 @@ See also ### I.1: Make interfaces explicit -**Reason**: Correctness. Assumptions not stated in an interface are easily overlooked and hard to test. +##### Reason + + Correctness. Assumptions not stated in an interface are easily overlooked and hard to test. + +##### Example, bad -**Example, bad**: Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example, int rnd(double d) @@ -892,7 +946,9 @@ It will not be obvious to a caller that the meaning of two calls of `rnd(7.2)` m **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. The use of a non-local control is potentially confusing, but controls only implementation details of an otherwise fixed semantics. -**Example, bad**: Reporting through non-local variables (e.g., `errno`) is easily ignored. For example: +##### Example, bad + + Reporting through non-local variables (e.g., `errno`) is easily ignored. For example: fprintf(connection, "logging: %d %d %d\n", x, y, s); // don't: no test of printf's return value @@ -906,16 +962,18 @@ Note that non-`const` member functions pass information to other member function **Alternative formulation**: An interface should be a function or a set of functions. Functions can be template functions and sets of functions can be classes or class templates. -**Enforcement**: +##### Enforcement * (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope. * (Simple) A function should not write to variables declared at namespace scope. ### I.2 Avoid global variables -**Reason**: Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes. +##### Reason -**Example**: + Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes. + +##### Example struct Data { // ... lots of stuff ... @@ -933,9 +991,13 @@ Functions can be template functions and sets of functions can be classes or clas Who else might modify `data`? -**Note**: Global constants are useful. +##### Note -**Note**: The rule against global variables applies to namespace scope variables as well. +Global constants are useful. + +##### Note + +The rule against global variables applies to namespace scope variables as well. **Alternative**: If you use global (more generally namespace scope data) to avoid copying, consider passing the data as an object by const reference. Another solution is to define the data as the state of some objects and the operations as member functions. @@ -943,18 +1005,23 @@ Another solution is to define the data as the state of some objects and the oper **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. Every pointer or reference to mutable data is a potential data race. -**Note**: You cannot have a race condition on immutable data. +##### Note + +You cannot have a race condition on immutable data. **Reference**: See the [rules for calling functions](#SS-call). -**Enforcement**: (Simple) Report all non-`const` variables declared at namespace scope. +##### Enforcement +(Simple) Report all non-`const` variables declared at namespace scope. ### I.3: Avoid singletons -**Reason**: Singletons are basically complicated global objects in disguise. +##### Reason -**Example**: + Singletons are basically complicated global objects in disguise. + +##### Example class Singleton { // ... lots of stuff to ensure that only one Singleton object is created, that it is initialized properly, etc. @@ -963,9 +1030,13 @@ Every pointer or reference to mutable data is a potential data race. There are many variants of the singleton idea. That's part of the problem. -**Note**: If you don't want a global object to change, declare it `const` or `constexpr`. +##### Note -**Exception**: You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any: +If you don't want a global object to change, declare it `const` or `constexpr`. + +##### Exception + +You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any: X& myX() { @@ -980,18 +1051,21 @@ In a multi-threaded environment the initialization of the static object does not 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. -**Enforcement**: Very hard in general +##### Enforcement + +Very hard in general * Look for classes with name that includes `singleton` * Look for classes for which only a single object is created (by counting objects or by examining constructors) - ### I.4: Make interfaces precisely and strongly typed Reason: Types are the simplest and best documentation, have well-defined meaning, and are guaranteed to be checked at compile time. Also, precisely typed code is often optimized better. -**Example; don't**: Consider +##### Example, don't + + Consider void pass(void* data); // void* is suspicious @@ -1001,7 +1075,9 @@ Consider using a variant or a pointer to base instead. (Future note: Consider a **Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or something like that. -**Example; bad**: Consider +##### Example, bad + +Consider void draw_rect(int, int, int, int); // great opportunities for mistakes @@ -1020,20 +1096,24 @@ Comments and parameter names can help, but we could be explicit: Obviously, we cannot catch all errors through the static type system (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)). +##### Example -**Example**: ??? units: time duration ??? +??? units: time duration ??? -**Enforcement**: +##### Enforcement * (Simple) Report the use of `void*` as a parameter or return type. * (Hard to do well) Look for member functions with many built-in type arguments. - ### I.5: State preconditions (if any) -**Reason**: Arguments have meaning that may constrain their proper use in the callee. +##### Reason -**Example**: Consider + Arguments have meaning that may constrain their proper use in the callee. + +##### Example + +Consider double sqrt(double x); @@ -1049,23 +1129,30 @@ Ideally, that `Expects(x>=0)` should be part of the interface of `sqrt()` but th **Reference**: `Expects()` is described in [GSL](#S-gsl). -**Note**: Prefer a formal specification of requirements, such as `Expects(p!=nullptr);` If that is infeasible, use English text in comments, such as +##### Note + +Prefer a formal specification of requirements, such as `Expects(p!=nullptr);` If that is infeasible, use English text in comments, such as `// the sequence [p:q) is ordered using <` -**Note**: Most member functions have as a precondition that some class invariant holds. +##### Note + +Most member functions have as a precondition that some class invariant holds. That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class. We don't need to mention it for each member function. -**Enforcement**: (Not enforceable) +##### Enforcement + +(Not enforceable) **See also**: The rules for passing pointers. - ### I.6: Prefer `Expects()` for expressing preconditions -**Reason**: To make it clear that the condition is a precondition and to enable tool use. +##### Reason -**Example**: + To make it clear that the condition is a precondition and to enable tool use. + +##### Example int area(int height, int width) { @@ -1074,20 +1161,31 @@ We don't need to mention it for each member function. // ... } -**Note**: 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?). +##### Note -**Note**: 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. +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?). -**Note**: `Expects()` can also be used to check a condition in the middle of an algorithm. +##### Note -**Enforcement**: (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. +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. +##### Note + +`Expects()` can also be used to check a condition in the middle of an algorithm. + +##### Enforcement + +(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. ### I.7: State postconditions -**Reason**: To detect misunderstandings about the result and possibly catch erroneous implementations. +##### Reason -**Example; bad**: Consider + To detect misunderstandings about the result and possibly catch erroneous implementations. + +##### Example, bad + +Consider int area(int height, int width) { return height*width; } // bad @@ -1103,7 +1201,9 @@ Consider using: return res; } -**Example, bad**: Consider a famous security bug +##### Example, bad + + Consider a famous security bug void f() // problematic { @@ -1122,11 +1222,17 @@ There was no postcondition stating that the buffer should be cleared and the opt Ensures(buffer[0]==0); } -**Note**: 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. +##### Note -**Note**: 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. +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. -**Example**: Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions: +##### Note + +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. + +##### Example + +Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions: mutex m; @@ -1154,18 +1260,23 @@ Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock m // ... } -**Note**: Ideally, postconditions are stated in the interface/declaration so that users can easily see them. +##### Note + +Ideally, postconditions are stated in the interface/declaration so that users can easily see them. Only postconditions related to the users can be stated in the interface. Postconditions related only to internal state belongs in the definition/implementation. -**Enforcement**: (Not enforceable) This is a philosophical guideline that is infeasible to check directly. +##### Enforcement +(Not enforceable) This is a philosophical guideline that is infeasible to check directly. ### I.8: Prefer `Ensures()` for expressing postconditions -**Reason**: To make it clear that the condition is a postcondition and to enable tool use. +##### Reason -**Example**: + To make it clear that the condition is a postcondition and to enable tool use. + +##### Example void f() { @@ -1175,20 +1286,27 @@ Postconditions related only to internal state belongs in the definition/implemen Ensures(buffer[0]==0); } -**Note**: 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. +##### Note + +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. **Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii). 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). -**Enforcement**: (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. +##### Enforcement +(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. ### I.9: If an interface is a template, document its parameters using concepts -**Reason**: Make the interface precisely specified and compile-time checkable in the (not so distant) future. +##### Reason -**Example**: Use the ISO Concepts TS style of requirements specification. For example: + Make the interface precisely specified and compile-time checkable in the (not so distant) future. + +##### Example + +Use the ISO Concepts TS style of requirements specification. For example: template // requires InputIterator && EqualityComparable>, Val> @@ -1197,19 +1315,24 @@ Ideally, that `Ensures` should be part of the interface, but that's not easily d // ... } -**Note**: Soon (maybe in 2016), most compilers will be able to check `requires` clauses once the `//` is removed. +##### Note + +Soon (maybe in 2016), most compilers will be able to check `requires` clauses once the `//` is removed. **See also**: See [generic programming](???) and [???](???) -**Enforcement**: (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). +##### Enforcement +(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). ### I.10: Use exceptions to signal a failure to perform a required task -**Reason**: It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state. +##### Reason + + It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state. This is a major source of errors. -**Example**: +##### Example int printf(const char* ...); // bad: return negative number if output fails @@ -1217,7 +1340,8 @@ This is a major source of errors. explicit thread(F&& f, Args&&... args); // good: throw system_error if unable to start the new thread -**Note**: What is an error? +##### Note: What is an error? + An error means that the function cannot achieve its advertised purpose (including establishing postconditions). Calling code that ignores the error could lead to wrong results or undefined systems state. For example, not being able to connect to a remote server is not by itself an error: @@ -1237,7 +1361,9 @@ consider using a style that returns a pair of values: } // ... use val ... -**Note**: We don't consider "performance" a valid reason not to use exceptions. +##### Note + +We don't consider "performance" a valid reason not to use exceptions. * Often, explicit error checking and handling consume as much time and space as exception handling. * Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization). @@ -1246,17 +1372,20 @@ consider using a style that returns a pair of values: **See also**: Rule I.??? and I.??? for reporting precondition and postcondition violations. -**Enforcement**: +##### Enforcement * (Not enforceable) This is a philosophical guideline that is infeasible to check directly. * Look for `errno`. - ### I.11: Never transfer ownership by a raw pointer (`T*`) -**Reason**: If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur. +##### Reason -**Example**: Consider + If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur. + +##### Example + +Consider X* compute(args) // don't { @@ -1295,11 +1424,13 @@ That is, its value must be `delete`d or transferred to another owner, as is done `owner` is defined in the [Guideline Support Library](#S-gsl). -**Note**: 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. +##### Note + +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. **See also**: [Argument passing](#Rf-conventional) and [value return](#Rf-T-return). -**Enforcement**: +##### Enforcement * (Simple) Warn on `delete` of a raw pointer that is not an `owner`. * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path. @@ -1308,9 +1439,11 @@ That is, its value must be `delete`d or transferred to another owner, as is done ### I.12: Declare a pointer that must not be null as `not_null` -**Reason**: To help avoid dereferencing `nullptr` errors. To improve performance by avoiding redundant checks for `nullptr`. +##### Reason -**Example**: + To help avoid dereferencing `nullptr` errors. To improve performance by avoiding redundant checks for `nullptr`. + +##### Example int length(const char* p); // it is not clear whether strlen(nullptr) is valid @@ -1322,24 +1455,29 @@ That is, its value must be `delete`d or transferred to another owner, as is done 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. -**Note**: 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*`. +##### Note + +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*`. int length(not_null p); // we can assume that p cannot be nullptr // we can assume that p points to a zero-terminated array of characters Note: `length()` is, of course, `std::strlen()` in disguise. -**Enforcement**: +##### Enforcement * (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`. * (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`. - ### I.13: Do not pass an array as a single pointer -**Reason**: (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. +##### Reason -**Example**: Consider + (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. + +##### Example + +Consider void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n) @@ -1351,7 +1489,9 @@ Either is undefined behavior and a potentially very nasty bug. void copy(array_view r, array_view r2); // copy r to r2 -**Example, bad**: Consider +##### Example, bad + + Consider void draw(Shape* p, int n); // poor interface; poor code Circle arr[10]; @@ -1375,17 +1515,20 @@ This `draw2()` passes the same amount of information to `draw()`, but makes the **Exception**: Use `zstring` and `czstring` to represent a C-style, zero-terminated strings. But see ???. -**Enforcement**: +##### Enforcement * (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. * (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. - ### I.14: Keep the number of function arguments low -**Reason**: Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives. +##### Reason -**Example**: The standard-library `merge()` is at the limit of what we can comfortably handle + Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives. + +##### Example + +The standard-library `merge()` is at the limit of what we can comfortably handle template OutputIterator merge(InputIterator1 first1, InputIterator1 last1, @@ -1408,24 +1551,29 @@ To really reduce the number of arguments, we need to bundle the arguments into h Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking. -**Note**: How many arguments are too many? Four arguments is a lot. +##### Note + +How many arguments are too many? Four arguments is a lot. There are functions that are best expressed with four individual arguments, but not many. **Alternative**: Group arguments into meaningful objects and pass the objects (by value or by reference). **Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments. -**Enforcement**: +##### Enforcement * Warn when a functions declares two iterators (including pointers) of the same type instead of a range or a view. * (Not enforceable) This is a philosophical guideline that is infeasible to check directly. - ### I.15: Avoid adjacent unrelated parameters of the same type -**Reason**: Adjacent arguments of the same type are easily swapped by mistake. +##### Reason -**Example; bad**: Consider + Adjacent arguments of the same type are easily swapped by mistake. + +##### Example, bad + +Consider void copy_n(T* p, T* q, int n); // copy from [p:p+n) to [q:q+n) @@ -1435,7 +1583,9 @@ Use `const` for the "from" argument: void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n) -**Example**: If the order of the parameters is not important, there is no problem: +##### Example + +If the order of the parameters is not important, there is no problem: int max(int a, int b); @@ -1443,14 +1593,19 @@ Use `const` for the "from" argument: void copy_n(array_view p, array_view q); // copy from p to q -**Enforcement**: (Simple) Warn if two consecutive parameters share the same type. +##### Enforcement +(Simple) Warn if two consecutive parameters share the same type. ### I.16: Prefer abstract classes as interfaces to class hierarchies -**Reason**: Abstract classes are more likely to be stable than base classes with state. +##### Reason -**Example; bad**: You just knew that `Shape` would turn up somewhere :-) + Abstract classes are more likely to be stable than base classes with state. + +##### Example, bad + +You just knew that `Shape` would turn up somewhere :-) class Shape { // bad: interface class loaded with data public: @@ -1475,21 +1630,27 @@ This will force every derived class to compute a center -- even if that's non-tr // ... no data members ... }; -**Enforcement**: (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. +##### Enforcement +(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. ### I.16: If you want a cross-compiler ABI, use a C-style subset -**Reason**: Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details. +##### Reason + + Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details. **Exception**: You can carefully craft an interface using a few carefully selected higher-level C++ types. See ???. **Exception**: Common ABIs are emerging on some platforms freeing you from the more draconian restrictions. -**Note**: 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. +##### Note -**Enforcement**: (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI. +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. +##### Enforcement + +(Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI. # F: Functions @@ -1553,10 +1714,12 @@ A function definition is a function declaration that also specifies the function ### F.1: "Package" meaningful operations as carefully named functions -**Reason**: Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code. +##### Reason + + Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code. If something is a well-specified action, separate it out from its surrounding code and give it a name. -**Example, don't**: +##### Example, don't void read_and_print(istream& is) // read and print an int { @@ -1573,10 +1736,12 @@ There is nothing to reuse, logically separate operations are intermingled and lo 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 mess could become hard to understand. -**Note**: If you write a non-trivial lambda that potentially can be used in more than one place, +##### Note + +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. -**Example**: +##### Example sort(a, b, [](T x, T y) { return x.valid() && y.valid() && x.value() F.2: A function should perform a single logical operation -**Reason**: A function that performs a single operation is simpler to understand, test, and reuse. +##### Reason -**Example**: Consider + A function that performs a single operation is simpler to understand, test, and reuse. + +##### Example + +Consider void read_and_print() // bad { @@ -1650,19 +1819,22 @@ If there was a need, we could further templatize `read()` and `print()` on the d output << value << "\n"; } -**Enforcement**: +##### Enforcement * Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values. * Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations. * Consider functions with 7 or more parameters suspicious. - ### F.3: Keep functions short and simple -**Reason**: Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes. +##### Reason + + Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes. Functions with complex control structures are more likely to be long and more likely to hide logical errors -**Example**: Consider +##### Example + +Consider double simpleFunc(double val, int flag1, int flag2) // simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags. @@ -1716,13 +1888,17 @@ We can refactor: return 0.; } -**Note**: "It doesn't fit on a screen" is often a good practical definition of "far too large." +##### Note + +"It doesn't fit on a screen" is often a good practical definition of "far too large." One-to-five-line functions should be considered normal. -**Note**: Break large functions up into smaller cohesive and named functions. +##### Note + +Break large functions up into smaller cohesive and named functions. Small simple functions are easily inlined where the cost of a function call is significant. -**Enforcement**: +##### Enforcement * Flag functions that do not "fit on a screen." How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page. @@ -1731,9 +1907,13 @@ Small simple functions are easily inlined where the cost of a function call is s ### F.4: If a function may have to be evaluated at compile time, declare it `constexpr` -**Reason**: `constexpr` is needed to tell the compiler to allow compile-time evaluation. +##### Reason -**Example**: The (in)famous factorial: + `constexpr` is needed to tell the compiler to allow compile-time evaluation. + +##### Example + +The (in)famous factorial: constexpr int fac(int n) { @@ -1746,7 +1926,9 @@ Small simple functions are easily inlined where the cost of a function call is s This is C++14. For C++11, use a recursive formulation of `fac()`. -**Note**: `constexpr` does not guarantee compile-time evaluation; +##### Note + +`constexpr` does not guarantee compile-time evaluation; 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. constexpr int min(int x, int y) { return x F.5: If a function is very small and time critical, declare it `inline` -**Reason**: Some optimizers are good at inlining without hints from the programmer, but don't rely on it. +##### Reason + + Some optimizers are good at inlining without hints from the programmer, but don't rely on it. Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans. We are still waiting. Specifying `inline` encourages the compiler to do a better job. @@ -1786,26 +1975,39 @@ Specifying `inline` encourages the compiler to do a better job. **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. An inline function is part of the ABI. -**Note**: `constexpr` implies `inline`. +##### Note -**Note**: Member functions defined in-class are `inline` by default. +`constexpr` implies `inline`. + +##### Note + +Member functions defined in-class are `inline` by default. **Exception**: Template functions (incl. template member functions) must be in headers and therefore inline. -**Enforcement**: Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions). -To fix: Declare the function out of line. (NM: Certainly possible, but size-based metrics can be very annoying.) +##### Enforcement +Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions). +To fix: Declare the function out of line. (NM: Certainly possible, but size-based metrics can be very annoying.) ### F.6: If your function may not throw, declare it `noexcept` -**Reason**: 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. +##### Reason -**Example**: Put `noexcept` on every function written completely in C or in any other language without exceptions. + 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. + +##### Example + +Put `noexcept` on every function written completely in C or in any other language without exceptions. The C++ standard library does that implicitly for all functions in the C standard library. -**Note**: `constexpr` functions cannot throw, so you don't need to use `noexcept` for those. +##### Note -**Example**: You can use `noexcept` even on functions that can throw: +`constexpr` functions cannot throw, so you don't need to use `noexcept` for those. + +##### Example + +You can use `noexcept` even on functions that can throw: vector collect(istream& is) noexcept { @@ -1819,63 +2021,74 @@ If `collect()` runs out of memory, the program crashes. Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do; `terminate()` may generate suitable error log information (but after memory runs out it is hard to do anything clever). -**Note**: In most programs, most functions can throw +##### Note + +In most programs, most functions can throw (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. `noexcept` is most useful for frequently used, low-level functions. -**Note**: Destructors, `swap` functions, move operations, and default constructors should never throw. +##### Note +Destructors, `swap` functions, move operations, and default constructors should never throw. -**Enforcement**: +##### Enforcement * Flag functions that are not `noexcept`, yet cannot throw. * Flag throwing `swap`, `move`, destructors, and default constructors. - ### F.7: For general use, take `T*` arguments rather than smart pointers -**Reason**: Passing a smart pointer transfers or shares ownership. +##### Reason + + Passing a smart pointer transfers or shares ownership. Passing by smart pointer restricts the use of a function to callers that use smart pointers. Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost. -**Example**: +##### Example void f(int*); // accepts any int* void g(unique_ptr); // can only accept ints for which you want to transfer ownership void g(shared_ptr); // can only accept ints for which you are willing to share ownership -**Note**: We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers. +##### Note + +We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers. **See also**: Discussion of [smart pointer use](#Rr-summary-smartptrs). -**Enforcement**: Flag smart pointer arguments. +##### Enforcement +Flag smart pointer arguments. ### F.8: Prefer pure functions +##### Reason -**Reason**: Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized. - -**Example**: + Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized. +##### Example template auto square(T t) { return t*t; } -**Note**: `constexpr` functions are pure. +##### Note -**Enforcement**: Not possible. +`constexpr` functions are pure. +##### Enforcement + +Not possible. ## F.call: Argument passing There are a variety of ways to pass arguments to a function and to return values. - ### Rule F.15: Prefer simple and conventional ways of passing information -**Reason**: Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs. +##### Reason + + Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs. 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. @@ -1885,15 +2098,15 @@ and document/comment because the improvement may not be portable. This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management. If you have multiple values to return, [use a tuple](#Rf-T-multi) or similar multi-member type. -**Example**: +##### Example vector find_all(const vector&, int x); // return pointers to elements with the value x -**Example, bad**: +##### Example, bad void find_all(const vector&, vector& out, int x); // place pointers to elements with value x in out -**Exceptions**: +##### Exceptions * For non-value types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`. * If a type is expensive to move (e.g., `array`), 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). @@ -1914,7 +2127,7 @@ For advanced uses (only), where you really need to optimize for rvalues passed t * 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).) * In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. (See [F.24](#Rf-pass-ref-ref).) -**Example**: +##### Example int multiply(int, int); // just input ints, pass by value @@ -1927,7 +2140,9 @@ Avoid "esoteric techniques" such as: * 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).) * Returning `const T&` from assignments and similar operations. -**Example**: Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`. +##### Example + +Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`. Matrix operator+(const Matrix& a, const Matrix& b) { @@ -1940,18 +2155,23 @@ Avoid "esoteric techniques" such as: y = m3+m3; // move assignment -**Note**: The (optional) return value optimization doesn't handle the assignment case. +##### Note + +The (optional) return value optimization doesn't handle the assignment case. **See also**: [implicit arguments](#Ri-explicit). -**Enforcement**: This is a philosophical guideline that is infeasible to check directly and completely. +##### Enforcement + +This is a philosophical guideline that is infeasible to check directly and completely. However, many of the detailed rules (F.16-F.45) can be checked, such as passing a `const int&`, returning an `array` by value, and returning a pointer to free store alloced by the function. - ### F.16: Use `T*` or `owner` to designate a single object -**Reason**: In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as +##### Reason + + In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as * Identify a (single) object (not to be deleted by this function) * Point to an object allocated on the free store (and delete it later) @@ -1963,8 +2183,9 @@ such as passing a `const int&`, returning an `array` by value, and retur For example, `not_null` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference. Additionally, when debugging, `owner` and `not_null` can be instrumented to check for correctness. +##### Example -**Example**: Consider +Consider int length(Record* p); @@ -1974,24 +2195,30 @@ When I call `length(r)` should I test for `r==nullptr` first? Should the impleme int length(Record* p); // the implementor of length() must assume that p==nullptr is possible -**Note**: A `not_null` 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). +##### Note -**Note**: `owner` represents ownership. +A `not_null` 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). + +##### Note + +`owner` represents ownership. **Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr`) points to a single element. **See also**: [Support library](#S-gsl). -**Enforcement**: +##### Enforcement * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. ### F.17: Use a `not_null` to indicate that "null" is not a valid value -**Reason**: Clarity. Making it clear that a test for null isn't needed. +##### Reason -**Example**: + Clarity. Making it clear that a test for null isn't needed. + +##### Example not_null check(T* p) { if (p) return not_null{p}; throw Unexpected_nullptr{}; } @@ -2002,20 +2229,23 @@ When I call `length(r)` should I test for `r==nullptr` first? Should the impleme } } -**Note**: `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. +##### Note -**Enforcement**: +`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. + +##### Enforcement * (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. * (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not. * (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function. - ### F.18: Use an `array_view` or an `array_view_p` to designate a half-open sequence -**Reason**: Informal/non-explicit ranges are a source of errors +##### Reason -**Example**: + Informal/non-explicit ranges are a source of errors + +##### Example X* find(array_view r, const X& v); // find v in r @@ -2023,25 +2253,34 @@ When I call `length(r)` should I test for `r==nullptr` first? Should the impleme // ... auto p = find({vec.begin(), vec.end()}, X{}); // find X{} in vec -**Note**: 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` and `array_view_p` 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. +##### Note -**Note**: An `array_view` object does not own its elements and is so small that it can be passed by value. +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` and `array_view_p` 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. -**Note**: 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. +##### Note + +An `array_view` object does not own its elements and is so small that it can be passed by value. + +##### Note + +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. **See also**: [Support library](#S-gsl). -**Enforcement**: (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `array_view` instead. +##### Enforcement +(Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `array_view` instead. ### F.19: Use a `zstring` or a `not_null` to designate a C-style string -**Reason**: +##### Reason + C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters. We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters. +##### Example -**Example**: Consider +Consider int length(const char* p); @@ -2051,16 +2290,19 @@ When I call `length(s)` should I test for `s==nullptr` first? Should the impleme int length(not_null p); // it is the caller's job to make sure p!=nullptr -**Note**: `zstring` do not represent ownership. +##### Note + +`zstring` do not represent ownership. **See also**: [Support library](#S-gsl). - ### F.20: Use a `const T&` parameter for a large object -**Reason**: Copying large objects can be expensive. A `const T&` is always cheap and protects the caller from unintended modification. +##### Reason -**Example**: + Copying large objects can be expensive. A `const T&` is always cheap and protects the caller from unintended modification. + +##### Example void fct(const string& s); // OK: pass by const reference; always cheap @@ -2068,21 +2310,25 @@ When I call `length(s)` should I test for `s==nullptr` first? Should the impleme **Exception**: Sinks (that is, a function that eventually destroys an object or passes it along to another sink), may benefit ??? -**Note**: A reference may be assumed to refer to a valid object (language rule). +##### Note + +A reference may be assumed to refer to a valid object (language rule). There is no (legitimate) "null reference." If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value." -**Enforcement**: +##### Enforcement * (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `4*sizeof(int)`. Suggest using a `const` reference instead. ### F.21: Use a `T` parameter for a small object -**Reason**: Nothing beats the simplicity and safety of copying. +##### Reason + + Nothing beats the simplicity and safety of copying. For small objects (up to two or three words) it is also faster than alternatives. -**Example**: +##### Example void fct(int x); // OK: Unbeatable @@ -2090,20 +2336,23 @@ For small objects (up to two or three words) it is also faster than alternatives void fct(int& x); // OK, but means something else; use only for an "out parameter" -**Enforcement**: +##### Enforcement * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference has a size less than `3*sizeof(int)`. Suggest passing by value instead. - ### F.22: Use a `T&` for an in-out-parameter -**Reason**: A called function can write to a non-`const` reference argument, so assume that it does. +##### Reason -**Example**: + A called function can write to a non-`const` reference argument, so assume that it does. + +##### Example void update(Record& r); // assume that update writes to r -**Note**: A `T&` argument can pass information into a function as well as well as out of it. +##### Note + +A `T&` argument can pass information into a function as well as well as out of it. Thus `T&` could be and in-out-parameter. That can in itself be a problem and a source of errors: void f(string& s) @@ -2122,17 +2371,18 @@ 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). If the writer of `g()` makes an assumption about the size of `buffer` a bad logic error can happen. -**Enforcement**: +##### Enforcement * (Moderate) ((Foundation)) Warn about functions with non-`const` reference arguments that do *not* write to them. * Flag functions that take a `T&` and replace the `T` referred to, rather what the contents of that `T` - ### F.23: Use `T&` for an out-parameter that is expensive to move (only) -**Reason**: 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). +##### Reason -**Example**: + 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). + +##### Example struct Package { char header[16]; @@ -2145,31 +2395,37 @@ If the writer of `g()` makes an assumption about the size of `buffer` a bad logi int val(); // OK void val(int&); // Bad: Is val reading its argument -**Enforcement**: Hard to choose a cutover value for the size of the value returned. +##### Enforcement +Hard to choose a cutover value for the size of the value returned. ### F.24: Use a `TP&&` parameter when forwarding (only) -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example template inline auto invoke(F&& f, Args&&... args) { return forward(f)(forward(args)...); } -**Enforcement**: Flag a function that takes a `TP&&` parameter (where `TP` is a template type parameter name) and uses it without `std::forward`. +##### Enforcement +Flag a function that takes a `TP&&` parameter (where `TP` is a template type parameter name) and uses it without `std::forward`. ### F.25: Use a `T&&` parameter together with `move` for rare optimization opportunities -**Reason**: Moving from an object leaves an object in its moved-from state behind. +##### Reason + + Moving from an object leaves an object in its moved-from state behind. In general, moved-from objects are dangerous. The only guaranteed operation is destruction (more generally, member functions without preconditions). The standard library additionally requires that a moved-from object can be assigned to. If you have performance justification to optimize for rvalues, overload on `&&` and then `move` from the parameter ([example of such overloading](#)). -**Example**: +##### Example void somefct(string&&); @@ -2182,17 +2438,18 @@ If you have performance justification to optimize for rvalues, overload on `&&` cout << s << '\n'; // Oops! What happens here? } -**Enforcement**: +##### Enforcement * Flag all `X&&` parameters (where `X` is not a template type parameter name) and code that uses them without `std::move`. * Flag access to moved-from objects. - ### F.26: Use a `unique_ptr` to transfer ownership where a pointer is needed -**Reason**: Using `unique_ptr` is the cheapest way to pass a pointer safely. +##### Reason -**Example**: + Using `unique_ptr` is the cheapest way to pass a pointer safely. + +##### Example unique_ptr get_shape(istream& is) // assemble shape from input stream { @@ -2205,16 +2462,21 @@ If you have performance justification to optimize for rvalues, overload on `&&` // ... } -**Note**: 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). +##### Note -**Enforcement**: (Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead. +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). +##### Enforcement + +(Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead. ### F.27: Use a `shared_ptr` to share ownership -**Reason**: Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object. +##### Reason -**Example**: + Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object. + +##### Example shared_ptr im { read_image(somewhere) }; @@ -2226,20 +2488,24 @@ If you have performance justification to optimize for rvalues, overload on `&&` // detach treads // last thread to finish deletes the image +##### Note -**Note**: Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time. +Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time. `shared_ptr` is for shared ownership. **Alternative**: Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completd. -**Enforcement**: (Not enforceable) This is a too complex pattern to reliably detect. +##### Enforcement +(Not enforceable) This is a too complex pattern to reliably detect. ### F.40: Prefer return values to out-parameters -**Reason**: It's self-documenting. A `&` parameter could be either in/out or out-only. +##### Reason -**Example**: + It's self-documenting. A `&` parameter could be either in/out or out-only. + +##### Example void incr(int&); int incr(int); @@ -2248,15 +2514,18 @@ If you have performance justification to optimize for rvalues, overload on `&&` incr(i); i = incr(i); -**Enforcement**: Flag non-const reference parameters that are not read before being written to and are a type that could be cheaply returned. +##### Enforcement +Flag non-const reference parameters that are not read before being written to and are a type that could be cheaply returned. ### F.41: Prefer to return tuples to multiple out-parameters -**Reason**: A return value is self-documenting as an "output-only" value. +##### Reason + + A return value is self-documenting as an "output-only" value. And yes, C++ does have multiple return values, by convention of using a `tuple`, with the extra convenience of `tie` at the call site. -**Example**: +##### Example int f( const string& input, /*output only*/ string& output_data ) { // BAD: output-only parameter documented in a comment // ... @@ -2286,22 +2555,28 @@ With C++11 we can write this, putting the results directly in existing local var **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. -**Note**: In some cases it may be useful to return a specific, user-defined `Value_or_error` type along the lines of `variant`, +##### Note + +In some cases it may be useful to return a specific, user-defined `Value_or_error` type along the lines of `variant`, rather than using the generic `tuple`. -**Enforcement**: +##### Enforcement * Output parameters should be replaced by return values. An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`. ### F.42: Return a `T*` to indicate a position (only) -**Reason**: That's what pointers are good for. +##### Reason + + That's what pointers are good for. Returning a `T*` to transfer ownership is a misuse. -**Note**: Do not return a pointer to something that is not in the caller's scope. +##### Note -**Example**: +Do not return a pointer to something that is not in the caller's scope. + +##### Example Node* find(Node* t, const string& s) // find s in a binary tree of Nodes { @@ -2314,9 +2589,11 @@ Returning a `T*` to transfer ownership is a misuse. If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`. Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller. -**Note**: Positions can also be transferred by iterators, indices, and references. +##### Note -**Example, bad**: +Positions can also be transferred by iterators, indices, and references. + +##### Example, bad int* f() { @@ -2336,17 +2613,22 @@ This applies to references as well: **See also**: [discussion of dangling pointer prevention](#???). -**Enforcement**: A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to. +##### Enforcement + +A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to. * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals. * Static analysis can catch most (all?) common patterns of the use of pointers indicating positions (thus eliminating dangling pointers) - ### F.43: Never (directly or indirectly) return a pointer to a local object -**Reason**: To avoid the crashes and data corruption that can result from the use of such a dangling pointer. +##### Reason -**Example**, bad: After the return from a function its local objects no longer exist: + To avoid the crashes and data corruption that can result from the use of such a dangling pointer. + +##### Example, bad + +After the return from a function its local objects no longer exist: int* f() { @@ -2384,12 +2666,18 @@ Imagine what a cracker could do with that dangling pointer. Fortunately, most (all?) modern compilers catch and warn against this simple case. -**Note**: You can construct similar examples using references. +##### Note -**Note**: This applies only to non-`static` local variables. +You can construct similar examples using references. + +##### Note + +This applies only to non-`static` local variables. All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle. -**Example**, bad: Not all examples of leaking a pointer to a local variable are that obvious: +##### Example, bad + +Not all examples of leaking a pointer to a local variable are that obvious: int* glob; // global variables are bad in so many ways @@ -2414,39 +2702,51 @@ All `static` variables are (as their name indicates) statically allocated, so th Here I managed to read the location abandoned by the call of `f`. The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways. -**Note**: The address of a local variable can be "returned"/leaked by a return statement, +##### Note + +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. -**Note**: Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one; +##### Note + +Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one; such examples are handled equivalently to leaks of pointers out of a function. **See also**: Another way of getting dangling pointers is [pointer invalidation](#???). It can be detected/prevented with similar techniques. -**Enforcement**: Preventable through static analysis. +##### Enforcement +Preventable through static analysis. ### F.44: Return a `T&` when "returning no object" isn't an option -**Reason**: The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary. +##### Reason + + The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary. **See also**: The return of a reference must not imply transfer of ownership: [discussion of dangling pointer prevention](#???) and [discussion of ownership](#???). -**Example**: +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### F.45: Don't return a `T&&` -**Reason**: 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). +##### Reason + + 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). 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&&`). -**Example; bad**: If `F` returns by value, this function returns a reference to a temporary. +##### Example, bad + +If `F` returns by value, this function returns a reference to a temporary. template auto&& wrapper(F f) { @@ -2454,7 +2754,9 @@ For passthrough functions that pass in parameters (by ordinary reference or by p return f(); } -**Example; good**: Better: +##### Example, good + +Better: template auto wrapper(F f) { @@ -2464,14 +2766,17 @@ For passthrough functions that pass in parameters (by ordinary reference or by p **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 `&&`. -**Enforcement**: Flag any use of `&&` as a return type, except in `std::move` and `std::forward`. +##### Enforcement +Flag any use of `&&` as a return type, except in `std::move` and `std::forward`. ### F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function) -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example // writing a function that should only take an int or a string -- overloading is natural void f(int); @@ -2493,18 +2798,18 @@ For passthrough functions that pass in parameters (by ordinary reference or by p **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. -**Enforcement**: +##### Enforcement * 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. - - ### F.51: Prefer overloading over default arguments for virtual functions ??? possibly other situations? -**Reason**: Virtual function overrides do not inherit default arguments, leading to surprises. +##### Reason -**Example; bad**: + Virtual function overrides do not inherit default arguments, leading to surprises. + +##### Example, bad class base { public: @@ -2522,14 +2827,19 @@ For passthrough functions that pass in parameters (by ordinary reference or by p b.multiply(10); // these two calls will call the same function but d.multiply(10); // with different arguments and so different results -**Enforcement**: Flag all uses of default arguments in virtual functions. +##### Enforcement +Flag all uses of default arguments in virtual functions. ### F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms -**Reason**: 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. +##### Reason -**Example**: 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. + 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. + +##### Example + +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. void send_packets( buffers& bufs ) { stage encryptor ([] (buffer& b){ encrypt(b); }); @@ -2538,14 +2848,17 @@ For passthrough functions that pass in parameters (by ordinary reference or by p for (auto& b : bufs) { decorator.process(b); } } // automatically blocks waiting for pipeline to finish -**Enforcement**: ??? +##### Enforcement +??? ### F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example { // ... @@ -2554,9 +2867,9 @@ For passthrough functions that pass in parameters (by ordinary reference or by p background_thread.queue_work([=]{ process(a, b, c); }); // want copies of a, b, and c } -**Enforcement**: ??? - +##### Enforcement +??? # C: Classes and Class Hierarchies @@ -2582,30 +2895,40 @@ Subsections: * [C.over: Overloading and overloaded operators](#SS-overload) * [C.union: Unions](#SS-union) - ### C.1: Organize related data into structures (`struct`s or `class`es) -**Reason**: Ease of comprehension. If data is related (for fundamental reasons), that fact should be reflected in code. +##### Reason -**Example**: + Ease of comprehension. If data is related (for fundamental reasons), that fact should be reflected in code. + +##### Example void draw(int x, int y, int x2, int y2); // BAD: unnecessary implicit relationships void draw(Point from, Point to); // better -**Note**: A simple class without virtual functions implies no space or time overhead. +##### Note -**Note**: From a language perspective `class` and `struct` differ only in the default visibility of their members. +A simple class without virtual functions implies no space or time overhead. -**Enforcement**: Probably impossible. Maybe a heuristic looking for data items used together is possible. +##### Note +From a language perspective `class` and `struct` differ only in the default visibility of their members. + +##### Enforcement + +Probably impossible. Maybe a heuristic looking for data items used together is possible. ### C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently -**Reason**: Ease of comprehension. The use of `class` alerts the programmer to the need for an invariant. +##### Reason -**Note**: 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`. + Ease of comprehension. The use of `class` alerts the programmer to the need for an invariant. -**Example**: +##### Note + +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`. + +##### Example struct Pair { // the members can vary independently string name; @@ -2624,14 +2947,17 @@ but // ... }; -**Enforcement**: Look for `struct`s with all data private and `class`es with public members. +##### Enforcement +Look for `struct`s with all data private and `class`es with public members. ### C.3: Represent the distinction between an interface and an implementation using a class -**Reason**: An explicit distinction between interface and implementation improves readability and simplifies maintenance. +##### Reason -**Example**: + An explicit distinction between interface and implementation improves readability and simplifies maintenance. + +##### Example class Date { // ... some representation ... @@ -2646,21 +2972,26 @@ but For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though). -**Note**: Using a class in this way to represent the distinction between interface and implementation is of course not the only way. +##### Note + +Using a class in this way to represent the distinction between interface and implementation is of course not the only way. 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. The most important issue is to explicitly distinguish between an interface and its implementation "details." Ideally, and typically, an interface is far more stable than its implementation(s). -**Enforcement**: ??? +##### Enforcement +??? ### C.4: Make a function a member only if it needs direct access to the representation of a class -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example class Date { // ... relatively small interface ... @@ -2672,19 +3003,24 @@ Ideally, and typically, an interface is far more stable than its implementation( The "helper functions" have no need for direct access to the representation of a `Date`. -**Note**: This rule becomes even better if C++17 gets "uniform function call." ??? +##### Note -**Enforcement**: Look for member function that do not touch data members directly. +This rule becomes even better if C++17 gets "uniform function call." ??? + +##### Enforcement + +Look for member function that do not touch data members directly. The snag is that many member functions that do not need to touch data members directly do. - ### C.5: Place helper functions in the same namespace as the class they support -**Reason**: 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, +##### Reason + + 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. 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. -**Example**: +##### Example namespace Chrono { // here we keep time-related services @@ -2697,23 +3033,27 @@ Placing them in the same namespace as the class makes their relationship to the // ... } -**Enforcement**: +##### Enforcement * Flag global functions taking argument types from a single namespace. - ### C.6: Declare a member function that does not modify the state of its object `const` -**Reason**: More precise statement of design intent, better readability, more errors caught by the compiler, more optimization opportunities. +##### Reason -**Example**: + More precise statement of design intent, better readability, more errors caught by the compiler, more optimization opportunities. + +##### Example int Date::day() const { return d; } -**Note**: [Do not cast away `const`](#Res-casts-const). +##### Note -**Enforcement**: Flag non-`const` member functions that do not write to their objects +[Do not cast away `const`](#Res-casts-const). +##### Enforcement + +Flag non-`const` member functions that do not write to their objects ## C.concrete: Concrete types @@ -2733,11 +3073,13 @@ Concrete type rule summary: ### C.10 Prefer a concrete type over more complicated classes -**Reason**: A concrete type is fundamentally simpler than a hierarchy: +##### Reason + + A concrete type is fundamentally simpler than a hierarchy: easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster. You need a reason (use cases) for using a hierarchy. -**Example** +##### Example class Point1 { int x, y; @@ -2765,21 +3107,28 @@ You need a reason (use cases) for using a hierarchy. 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. That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections. -**Note**: Concrete types can be stack allocated and be members of other classes. +##### Note -**Note**: The use of indirection is fundamental for run-time polymorphic interfaces. +Concrete types can be stack allocated and be members of other classes. + +##### Note + +The use of indirection is fundamental for run-time polymorphic interfaces. The allocation/deallocation overhead is not (that's just the most common case). We can use a base class as the interface of a scoped object of a derived class. 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. -**Enforcement**: ??? +##### Enforcement +??? ### C.11: Make concrete types regular -**Reason**: Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use). +##### Reason -**Example**: + Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use). + +##### Example struct Bundle { string name; @@ -2796,8 +3145,9 @@ This is done where dynamic allocation is prohibited (e.g. hard real-time) and to In particular, if a concrete type has an assignment also give it an equals operator so that `a=b` implies `a==b`. -**Enforcement**: ??? +##### Enforcement +??? ## C.ctor: Constructors, assignments, and destructors @@ -2884,9 +3234,11 @@ However, a programmer can disable or replace these defaults. ### C.20: If you can avoid defining default operations, do -**Reason**: It's the simplest and gives the cleanest semantics. +##### Reason -**Example**: + It's the simplest and gives the cleanest semantics. + +##### Example struct Named_map { public: @@ -2901,17 +3253,22 @@ However, a programmer can disable or replace these defaults. Since `std::map` and `string` have all the special functions, no further work is needed. -**Note**: This is known as "the rule of zero". +##### Note -**Enforcement**: (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule. +This is known as "the rule of zero". + +##### Enforcement + +(Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule. 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`. - ### C.21: If you define or `=delete` any default operation, define or `=delete` them all -**Reason**: The semantics of the special functions are closely related, so it one needs to be non-default, the odds are that other need modification. +##### Reason -**Example, bad**: + The semantics of the special functions are closely related, so it one needs to be non-default, the odds are that other need modification. + +##### Example, bad struct M2 { // bad: incomplete set of default operations public: @@ -2933,24 +3290,35 @@ Since `std::map` and `string` have all the special functions, no further work is 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). -**Note**: This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor. +##### Note -**Note**: 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. +This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor. + +##### Note + +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. If you don't want a default operation, suppress it with `=delete`. -**Note:** Compilers enforce much of this rule and ideally warn about any violation. +##### Note -**Note**: Relying on an implicitly generated copy operation in a class with a destructor is deprecated. +Compilers enforce much of this rule and ideally warn about any violation. -**Enforcement**: (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions. +##### Note +Relying on an implicitly generated copy operation in a class with a destructor is deprecated. + +##### Enforcement + +(Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions. ### C.22: Make default operations consistent -**Reason**: The default operations are conceptually a matched set. Their semantics are interrelated. +##### Reason + + The default operations are conceptually a matched set. Their semantics are interrelated. 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. -**Example; bad**: +##### Example, bad class Silly { // BAD: Inconsistent copy operations class Impl { @@ -2965,15 +3333,13 @@ Users will be surprised if copy/move construction and copy/move assignment do lo These operations disagree about copy semantics. This will lead to confusion and bugs. -**Enforcement**: +##### Enforcement * (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. * (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors. * (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable. * (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators. - - ## C.dtor: Destructors "Does this class need a destructor?" is a surprisingly powerful design question. @@ -2981,14 +3347,15 @@ For most classes the answer is "no" either because the class holds no resources that is, its members can take care of themselves as concerns destruction. If the answer is "yes", much of the design of the class follows (see [the rule of five](#Rc-five). - ### C.30: Define a destructor if a class needs an explicit action at object destruction -**Reason**: A destructor is implicitly invoked at the end of an object's lifetime. +##### Reason + + A destructor is implicitly invoked at the end of an object's lifetime. If the default destructor is sufficient, use it. Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors. -**Example**: +##### Example template struct final_action { // slightly simplified @@ -3013,12 +3380,14 @@ Only define a non-default destructor if a class needs to execute code that is no The whole purpose of `final_action` is to get a piece of code (usually a lambda) executed upon destruction. -**Note**: There are two general categories of classes that need a user-defined destructor: +##### Note + +There are two general categories of classes that need a user-defined destructor: * A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class. * A class that exists primarily to execute an action upon destruction, such as a tracer or `final_action`. -**Example, bad**: +##### Example, bad class Foo { // bad; use the default destructor public: @@ -3032,18 +3401,25 @@ The whole purpose of `final_action` is to get a piece of code (usually a lambda) The default destructor does it better, more efficiently, and can't get it wrong. -**Note**: If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`. +##### Note -**Enforcement**: Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors. +If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`. +##### Enforcement + +Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors. ### C.31: All resources acquired by a class must be released by the class's destructor -**Reason**: Prevention of resource leaks, especially in error cases. +##### Reason -**Note**: For resources represented as classes with a complete set of default operations, this happens automatically. + Prevention of resource leaks, especially in error cases. -**Example**: +##### Note + +For resources represented as classes with a complete set of default operations, this happens automatically. + +##### Example class X { ifstream f; // may own a file @@ -3052,7 +3428,7 @@ The default destructor does it better, more efficiently, and can't get it wrong. `X`'s `ifstream` implicitly closes any file it may have open upon destruction of its `X`. -**Example; bad**: +##### Example, bad class X2 { // bad FILE* f; // may own a file @@ -3061,7 +3437,9 @@ The default destructor does it better, more efficiently, and can't get it wrong. `X2` may leak a file handle. -**Note**: What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail). +##### Note + +What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail). If it does nevertheless, we have a problem that has no really good solution. For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception. See [discussion](#Sd-never-fail). @@ -3069,7 +3447,9 @@ To make the problem worse, many "close/release" operations are not retryable. Many have tried to solve this problem, but no general solution is known. If at all possible, consider failure to close/cleanup a fundamental design error and terminate. -**Note**: A class can hold pointers and references to objects that it does not own. +##### Note + +A class can hold pointers and references to objects that it does not own. Obviously, such objects should not be `delete`d by the class's destructor. For example: @@ -3079,7 +3459,7 @@ For example: Here `p` refers to `pp` but does not own it. -**Enforcement**: +##### Enforcement * (Simple) If a class has pointer or reference member variables that are owners (e.g., deemed owners by using `gsl::owner`), then they should be referenced in its destructor. @@ -3088,23 +3468,32 @@ Here `p` refers to `pp` but does not own it. ### C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning -**Reason**: There is a lot of code that is non-specific about ownership. +##### Reason -**Example**: + There is a lot of code that is non-specific about ownership. + +##### Example ??? -**Note**: If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`. +##### Note + +If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`. This will aide documentation and analysis. -**Enforcement**: Look at the initialization of raw member pointers and member references and see if an allocation is used. +##### Enforcement +Look at the initialization of raw member pointers and member references and see if an allocation is used. ### C.33: If a class has an owning pointer member, define a destructor -**Reason**: An owned object must be `deleted` upon destruction of the object that owns it. +##### Reason -**Example**: A pointer member may represent a resource. + An owned object must be `deleted` upon destruction of the object that owns it. + +##### Example + +A pointer member may represent a resource. [A `T*` should not do so](#Rr-ptr), but in older code, that's common. Consider a `T*` a possible owner and therefore suspect. @@ -3155,26 +3544,31 @@ The default copy operation will just copy the `p1.p` into `p2.p` leading to a do } - **Note**: Often the simplest way to get a destructor is to replace the pointer with a smart pointer (e.g., `std::unique_ptr`) + ##### Note + +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. -**Note**: Why not just require all owning pointers to be "smart pointers"? +##### Note + +Why not just require all owning pointers to be "smart pointers"? That would sometimes require non-trivial code changes and may affect ABIs. -**Enforcement**: +##### Enforcement * A class with a pointer data member is suspect. * A class with an `owner` should define its default operations. - ### C.34: If a class has an owning reference member, define a destructor -**Reason**: A reference member may represent a resource. +##### Reason + + A reference member may represent a resource. It should not do so, but in older code, that's common. See [pointer members and destructors](#Rc-dtor-ptr). Also, copying may lead to slicing. -**Example, bad**: +##### Example, bad class Handle { // Very suspect Shape& s; // use reference rather than pointer to prevent rebinding @@ -3188,7 +3582,7 @@ Also, copying may lead to slicing. The problem of whether `Handle` is responsible for the destruction of its `Shape` is the same as for [the pointer case](#Rc-dtor-ptr): If the `Handle` owns the object referred to by `s` it must have a destructor. -**Example**: +##### Example class Handle { // OK owner s; // use reference rather than pointer to prevent rebinding @@ -3209,25 +3603,27 @@ That `x=y` is highly suspect. Assigning a `Triangle` to a `Circle`? Unless `Shape` has its [copy assignment `=deleted`](#Rc-copy-virtual), only the `Shape` part of `Triangle` is copied into the `Circle`. +##### Note -**Note**: Why not just require all owning references to be replaced by "smart pointers"? +Why not just require all owning references to be replaced by "smart pointers"? Changing from references to smart pointers implies code changes. We don't (yet) have smart references. Also, that may affect ABIs. -**Enforcement**: +##### Enforcement * A class with a reference data member is suspect. * A class with an `owner` reference should define its default operations. - ### C.35: A base class with a virtual function needs a virtual destructor -**Reason**: To prevent undefined behavior. +##### Reason + + To prevent undefined behavior. 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. In general, the writer of a base class does not know the appropriate action to be done upon destruction. -**Example; bad**: +##### Example, bad struct Base { // BAD: no virtual destructor virtual f(); @@ -3245,10 +3641,14 @@ In general, the writer of a base class does not know the appropriate action to b // ... } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more -**Note**: A virtual function defines an interface to derived classes that can be used without looking at the derived classes. +##### Note + +A virtual function defines an interface to derived classes that can be used without looking at the derived classes. Someone using such an interface is likely to also destroy using that interface. -**Note**: A destructor must be `public` or it will prevent stack allocation and normal heap allocation via smart pointer (or in legacy code explicit `delete`): +##### Note + +A destructor must be `public` or it will prevent stack allocation and normal heap allocation via smart pointer (or in legacy code explicit `delete`): class X { ~X(); // private destructor @@ -3261,15 +3661,18 @@ Someone using such an interface is likely to also destroy using that interface. auto p = make_unique(); // error: cannot destroy } -**Enforcement**: (Simple) A class with any virtual functions should have a virtual destructor. +##### Enforcement +(Simple) A class with any virtual functions should have a virtual destructor. ### C.36: A destructor may not fail -**Reason**: In general we do not know how to write error-free code if a destructor should fail. +##### Reason + + In general we do not know how to write error-free code if a destructor should fail. The standard library requires that all classes it deals with have destructors that do not exit by throwing. -**Example**: +##### Example class X { public: @@ -3284,7 +3687,9 @@ The standard library requires that all classes it deals with have destructors th // ... } -**Note**: Many have tried to devise a fool-proof scheme for dealing with failure in destructors. +##### Note + +Many have tried to devise a fool-proof scheme for dealing with failure in destructors. None have succeeded to come up with a general scheme. This can be be a real practical problem: For example, what about a sockets that won't close? The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception. @@ -3292,39 +3697,49 @@ See [discussion](#Sd-dtor). To make the problem worse, many "close/release" operations are not retryable. If at all possible, consider failure to close/cleanup a fundamental design error and terminate. -**Note**: Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program. +##### Note -**Note**: If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow +Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program. + +##### Note + +If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow (maybe even by modifying some global state and hope something will notice and be able to take care of the problem). Be fully aware that this technique is special-purpose and error-prone. Consider the "my connection will not close" example. 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. The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally. -**Note**: If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully +##### Note + +If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully (e.g., by using a different clean-up mechanism from the one that threw an exception). -**Enforcement**: (Simple) A destructor should be declared `noexcept`. +##### Enforcement +(Simple) A destructor should be declared `noexcept`. ### C.37: Make destructors `noexcept` -**Reason**: [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. +##### Reason -**Enforcement**: (Simple) A destructor should be declared `noexcept`. + [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. +##### Enforcement +(Simple) A destructor should be declared `noexcept`. ## C.ctor: Constructors A constructor defined how an object is initialized (constructed). - ### C.40: Define a constructor if a class has an invariant -**Reason**: That's what constructors are for. +##### Reason -**Example**: + That's what constructors are for. + +##### Example class Date { // a Date represents a valid date // in the January 1, 1900 to December 31, 2100 range @@ -3340,7 +3755,9 @@ A constructor defined how an object is initialized (constructed). It is often a good idea to express the invariant as an `Ensure` on the constructor. -**Note**: A constructor can be used for convenience even if a class does not have an invariant. For example: +##### Note + +A constructor can be used for convenience even if a class does not have an invariant. For example: struct Rec { string s; @@ -3352,7 +3769,9 @@ It is often a good idea to express the invariant as an `Ensure` on the construct Rec r1 {7}; Rec r2 {"Foo bar"}; -**Note**: The C++11 initializer list rules eliminates the need for many constructors. For example: +##### Note + +The C++11 initializer list rules eliminates the need for many constructors. For example: struct Rec2{ string s; @@ -3368,16 +3787,17 @@ Also, the default for `int` would be better done as a [member initializer](#Rc-i **See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw). -**Enforcement**: +##### Enforcement * Flag classes with user-define copy operations but no destructor (a user-defined copy is a good indicator that the class has an invariant) - ### C.41: A constructor should create a fully initialized object -**Reason**: A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable. +##### Reason -**Example; bad**: + A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable. + +##### Example, bad class X1 { FILE* f; // call init() before any other function @@ -3402,15 +3822,18 @@ Compilers do not read comments. **Exception**: If a valid object cannot conveniently be constructed by a constructor [use a factory function](#Rc-factory). -**Note**: If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release). -The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisitions Is Initialization"). +##### Note +If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-dtor-release). +The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisitions Is Initialization"). ### C.42: If a constructor cannot construct a valid object, throw an exception -**Reason**: Leaving behind an invalid object is asking for trouble. +##### Reason -**Example**: + Leaving behind an invalid object is asking for trouble. + +##### Example class X2 { FILE* f; // call init() before any other function @@ -3434,7 +3857,7 @@ The idiom of having constructors acquire resources and destructors release them // ... } -**Example, bad**: +##### Example, bad class X3 { // bad: the constructor leaves a non-valid object behind FILE* f; // call init() before any other function @@ -3468,23 +3891,27 @@ The idiom of having constructors acquire resources and destructors release them // ... } -**Note**: 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. +##### Note + +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. **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). **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). -**Enforcement**: +##### Enforcement + * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction). * (Unknown) If a constructor has an `Ensures` contract, try to see if it holds as a postcondition. - ### C.43: Give a class a default constructor -**Reason**: Many language and library facilities rely on default constructors, +##### Reason + + Many language and library facilities rely on default constructors, e.g. `T a[10]` and `std::vector v(10)` default initializes their elements. -**Example**: +##### Example class Date { public: @@ -3499,16 +3926,18 @@ There is no "natural" default date (the big bang is too far back in time to be u `{0, 0, 0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's NaN. However, most realistic `Date` classes has a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial. -**Enforcement**: +##### Enforcement * Flag classes without a default constructor ### C.44: Prefer default constructors to be simple and non-throwing -**Reason**: Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations. +##### Reason -**Example, problematic**: + Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations. + +##### Example, problematic template class Vector0 { // elem points to space-elem element allocated using new @@ -3526,7 +3955,7 @@ This is nice and general, but setting a `Vector0` to empty after an error involv Also, having a default `Vector` represented as `{new T[0], 0, 0}` seems wasteful. For example, `Vector0 v(100)` costs 100 allocations. -**Example**: +##### Example template class Vector1 { // elem is nullptr or elem points to space-elem element allocated using new @@ -3543,16 +3972,17 @@ For example, `Vector0 v(100)` costs 100 allocations. Using `{nullptr, nullptr, nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks. Setting a `Vector1` to empty after detecting an error is trivial. -**Enforcement**: +##### Enforcement * Flag throwing default constructors - ### C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead -**Reason**: Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient. +##### Reason -**Example; bad**: + Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient. + +##### Example, bad class X1 { // BAD: doesn't use member initializers string s; @@ -3562,7 +3992,7 @@ Setting a `Vector1` to empty after detecting an error is trivial. // ... }; -**Example**: +##### Example class X2 { string s = "default"; @@ -3572,15 +4002,17 @@ Setting a `Vector1` to empty after detecting an error is trivial. // ... }; +##### Enforcement -**Enforcement**: (Simple) A default constructor should do more than just initialize member variables with constants. - +(Simple) A default constructor should do more than just initialize member variables with constants. ### C.46: By default, declare single-argument constructors explicit -**Reason**: To avoid unintended conversions. +##### Reason -**Example; bad**: + To avoid unintended conversions. + +##### Example, bad class String { // ... @@ -3591,8 +4023,9 @@ Setting a `Vector1` to empty after detecting an error is trivial. String s = 10; // surprise: string of size 10 +##### Exception -**Exception**: If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`: +If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`: class Complex { // ... @@ -3605,14 +4038,17 @@ Setting a `Vector1` to empty after detecting an error is trivial. **See also**: [Discussion of implicit conversions](#Ro-conversion). -**Enforcement**: (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". +##### Enforcement +(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". ### C.47: Define and initialize member variables in the order of member declaration -**Reason**: To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers). +##### Reason -**Example; bad**: + To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers). + +##### Example, bad class Foo { int m1; @@ -3624,16 +4060,19 @@ Setting a `Vector1` to empty after detecting an error is trivial. Foo x(1); // surprise: x.m1==x.m2==2 -**Enforcement**: (Simple) A member initializer list should mention the members in the same order they are declared. +##### Enforcement + +(Simple) A member initializer list should mention the members in the same order they are declared. **See also**: [Discussion](#Sd-order) - ### C.48: Prefer in-class initializers to member initializers in constructors for constant initializers -**Reason**: 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. +##### Reason -**Example; bad**: + 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. + +##### Example, bad class X { // BAD int i; @@ -3647,7 +4086,7 @@ Setting a `Vector1` to empty after detecting an error is trivial. 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. -**Example**: +##### Example class X2 { int i {666}; @@ -3671,16 +4110,18 @@ How would a maintainer know whether `j` was deliberately uninitialized (probably // ... }; -**Enforcement**: +##### Enforcement + * (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction). * (Simple) Default arguments to constructors suggest an in-class initializer may be more appropriate. - ### C.49: Prefer initialization to assignment in constructors -**Reason**: An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors. +##### Reason -**Example; good**: + An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors. + +##### Example, good class A { // Good string s1; @@ -3689,7 +4130,7 @@ How would a maintainer know whether `j` was deliberately uninitialized (probably // ... }; -**Example; bad**: +##### Example, bad class B { // BAD string s1; @@ -3705,14 +4146,14 @@ How would a maintainer know whether `j` was deliberately uninitialized (probably // ... }; - - ### C.50: Use a factory function if you need "virtual behavior" during initialization -**Reason**: If the state of a base class object must depend on the state of a derived part of the object, +##### Reason + + 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. -**Example; bad**: +##### Example, bad class B { public: @@ -3728,7 +4169,7 @@ How would a maintainer know whether `j` was deliberately uninitialized (probably // ... }; -**Example*: +##### Example class B { protected: @@ -3760,16 +4201,19 @@ How would a maintainer know whether `j` was deliberately uninitialized (probably By making the constructor `protected` we avoid an incompletely constructed object escaping into the wild. By providing the factory function `Create()`, we make construction (on the free store) convenient. -**Note**: Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object. +##### Note + +Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object. **See also**: [Discussion](#Sd-factory) - ### C.51: Use delegating constructors to represent common actions for all constructors of a class -**Reason**: To avoid repetition and accidental differences +##### Reason -**Example; bad**: + To avoid repetition and accidental differences + +##### Example, bad class Date { // BAD: repetitive int d; @@ -3788,8 +4232,7 @@ By providing the factory function `Create()`, we make construction (on the free The common action gets tedious to write and may accidentally not be common. -**Example**: - +##### Example class Date2 { int d; @@ -3807,14 +4250,19 @@ The common action gets tedious to write and may accidentally not be common. **See also**: If the "repeated action" is a simple initialization, consider [an in-class member initializer](#Rc-in-class-initializer). -**Enforcement**: (Moderate) Look for similar constructor bodies. +##### Enforcement +(Moderate) Look for similar constructor bodies. ### C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization -**Reason**: If you need those constructors for a derived class, re-implementeing them is tedious and error prone. +##### Reason -**Example**: `std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them: + If you need those constructors for a derived class, re-implementeing them is tedious and error prone. + +##### Example + +`std::vector` has a lot of tricky constructors, so if I want my own `vector`, I don't want to reimplement them: class Rec { // ... data and lots of nice constructors ... @@ -3826,7 +4274,7 @@ The common action gets tedious to write and may accidentally not be common. // ... lots of nice utility functions ... }; -**Example; bad**: +##### Example, bad struct Rec2 : public Rec { int x; @@ -3836,10 +4284,9 @@ The common action gets tedious to write and may accidentally not be common. Rec2 r {"foo", 7}; int val = r.x; // uninitialized +##### Enforcement -**Enforcement**: Make sure that every member of the derived class is initialized. - - +Make sure that every member of the derived class is initialized. ## C.copy: Copy and move @@ -3847,12 +4294,13 @@ Value type should generally be copyable, but interfaces in a class hierarchy sho Resource handles, may or may not be copyable. Types can be defined to move for logical as well as performance reasons. - ### C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&` -**Reason**: 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)). +##### Reason -**Example**: + 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)). + +##### Example class Foo { public: @@ -3872,9 +4320,13 @@ Types can be defined to move for logical as well as performance reasons. a = b; // assign lvalue: copy a = f(); // assign rvalue: potentially move -**Note**: The `swap` implementation technique offers the [strong guarantee](???). +##### Note -**Example**: 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: +The `swap` implementation technique offers the [strong guarantee](???). + +##### Example + +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: template class Vector { @@ -3906,7 +4358,7 @@ By writing directly to the target elements, we will get only [the basic guarante **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&)`. See [copy constructor vs. `clone()`](#Rc-copy-virtual). -**Enforcement**: +##### Enforcement * (Simple) An assignment operator should not be virtual. Here be dragons! * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers. @@ -3915,10 +4367,12 @@ See [copy constructor vs. `clone()`](#Rc-copy-virtual). ### C.61: A copy operation should copy -**Reason**: That is the generally assumed semantics. After `x=y`, we should have `x==y`. +##### Reason + + That is the generally assumed semantics. After `x=y`, we should have `x==y`. 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). -**Example**: +##### Example class X { // OK: value semantics public: @@ -3949,7 +4403,7 @@ After a copy `x` and `y` can be independent objects (value semantics, the way no x.modify(); if (x==y) throw Bad{}; // assume value semantics -**Example**: +##### Example class X2 { // OK: pointer semantics public: @@ -3974,22 +4428,31 @@ After a copy `x` and `y` can be independent objects (value semantics, the way no x.modify(); if (x!=y) throw Bad{}; // assume pointer semantics -**Note**: 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. +##### Note -**Enforcement**: (Not enforceable). +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. +##### Enforcement + +(Not enforceable). ### C.62: Make copy assignment safe for self-assignment -**Reason**: If `x=x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks). +##### Reason -**Example**: The standard-library containers handle self-assignment elegantly and efficiently: + If `x=x` changes the value of `x`, people will be surprised and bad errors will occur (often including leaks). + +##### Example + +The standard-library containers handle self-assignment elegantly and efficiently: std::vector v = {3, 1, 4, 1, 5, 9}; v = v; // the value of v is still {3, 1, 4, 1, 5, 9} -**Note**: The default assignment generated from members that handle self-assignment correctly handles self-assignment. +##### Note + +The default assignment generated from members that handle self-assignment correctly handles self-assignment. struct Bar { vector> v; @@ -4001,7 +4464,9 @@ After a copy `x` and `y` can be independent objects (value semantics, the way no // ... b = b; // correct and efficient -**Note**: 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)). +##### Note + +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)). class Foo { string s; @@ -4033,26 +4498,32 @@ Consider: `std::string` is safe for self-assignment and so are `int`. All the cost is carried by the (rare) case of self-assignment. -**Enforcement**: (Simple) Assignment operators should not contain the pattern `if (this==&a) return *this;` ??? +##### Enforcement +(Simple) Assignment operators should not contain the pattern `if (this==&a) return *this;` ??? ### C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const &` -**Reason**: It is simple and efficient. +##### Reason + + It is simple and efficient. **See**: [The rule for copy-assignment](#Rc-copy-assignment). -**Enforcement**: Equivalent to what is done for [copy-assignment](#Rc-copy-assignment). +##### Enforcement + +Equivalent to what is done for [copy-assignment](#Rc-copy-assignment). * (Simple) An assignment operator should not be virtual. Here be dragons! * (Simple) An assignment operator should return `T&` to enable chaining, not alternatives like `const T&` which interfere with composability and putting objects in containers. * (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators. - ### C.64: A move operation should move and leave its source in valid state -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example template class X { // OK: value semantics @@ -4083,19 +4554,26 @@ Consider: x = X{}; // OK } // OK: x can be destroyed -**Note**: 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. +##### Note + +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. 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. -**Note**: Unless there is an exceptionally strong reason not to, make `x=std::move(y); y=z;` work with the conventional semantics. +##### Note -**Enforcement**: (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. +Unless there is an exceptionally strong reason not to, make `x=std::move(y); y=z;` work with the conventional semantics. +##### Enforcement + +(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. ### C.65: Make move assignment safe for self-assignment -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example class Foo { string s; @@ -4115,11 +4593,17 @@ Often, we can easily and cheaply do better: The standard library assumes that it 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. -**Note**: 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). +##### Note -**Note** 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. +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). -**Example**: Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment): +##### Note + +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. + +##### Example + +Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment): // move from other.oter to this->ptr T* temp = other.ptr; @@ -4127,18 +4611,19 @@ The one-in-a-million argument against `if (this==&a) return *this;` tests from t delete ptr; ptr = temp; -**Enforcement**: +##### Enforcement * (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. * (Not enforceable) Look at the use of standard-library container types (incl. `string`) and consider them safe for ordinary (not life-critical) uses. - ### C.66: Make move operations `noexcept` -**Reason**: A throwing move violates most people's reasonably assumptions. +##### Reason + + A throwing move violates most people's reasonably assumptions. A non-throwing move will be used more efficiently by standard-library and language facilities. -**Example**: +##### Example template class Vector { @@ -4153,7 +4638,7 @@ A non-throwing move will be used more efficiently by standard-library and langua These copy operations do not throw. -**Example, bad**: +##### Example, bad template class Vector2 { @@ -4168,16 +4653,17 @@ These copy operations do not throw. This `Vector2` is not just inefficient, but since a vector copy requires allocation, it can throw. -**Enforcement**: (Simple) A move operation should be marked `noexcept`. - - +##### Enforcement +(Simple) A move operation should be marked `noexcept`. ### C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired -**Reason**: To prevent slicing, because the normal copy operations will copy only the base portion of a derived object. +##### Reason -**Example; bad**: + To prevent slicing, because the normal copy operations will copy only the base portion of a derived object. + +##### Example, bad class B { // BAD: base class doesn't suppress copying int data; @@ -4192,7 +4678,7 @@ This `Vector2` is not just inefficient, but since a vector copy requires allocat auto d = make_unique(); auto b = make_unique(d); // oops, slices the object; gets only d.data but drops d.moredata -**Example**: +##### Example class B { // GOOD: base class suppresses copying B(const B&) =delete; @@ -4210,11 +4696,13 @@ This `Vector2` is not just inefficient, but since a vector copy requires allocat auto d = make_unique(); auto b = d.clone(); // ok, deep clone -**Note**: 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`. 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. +##### Note -**Enforcement**: A class with any virtual function should not have a copy constructor or copy assignment operator (compiler-generated or handwritten). +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`. 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. +##### Enforcement +A class with any virtual function should not have a copy constructor or copy assignment operator (compiler-generated or handwritten). ## C.other: Other default operations @@ -4222,9 +4710,11 @@ This `Vector2` is not just inefficient, but since a vector copy requires allocat ### C.80: Use `=default` if you have to be explicit about using the default semantics -**Reason**: The compiler is more likely to get the default semantics right and you cannot implement these function better than the compiler. +##### Reason -**Example**: + The compiler is more likely to get the default semantics right and you cannot implement these function better than the compiler. + +##### Example class Tracer { string message; @@ -4240,7 +4730,7 @@ This `Vector2` is not just inefficient, but since a vector copy requires allocat Because we defined the destructor, we must define the copy and move operations. The `=default` is the best and simplest way of doing that. -**Example, bad**: +##### Example, bad class Tracer2 { string message; @@ -4256,14 +4746,17 @@ Because we defined the destructor, we must define the copy and move operations. Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better. -**Enforcement**: (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 +##### Enforcement +(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 ### C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative) -**Reason**: In a few cases, a default operation is not desirable. +##### Reason -**Example**: + In a few cases, a default operation is not desirable. + +##### Example class Immortal { public: @@ -4278,7 +4771,9 @@ Writing out the bodies of the copy and move operations is verbose, tedious, and delete p; // error: cannot destroy *p } -**Example**: 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: +##### Example + +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: template > class unique_ptr { public: @@ -4301,15 +4796,19 @@ Writing out the bodies of the copy and move operations is verbose, tedious, and auto pi3 {make()}; // OK, move: the result of make() is an rvalue } -**Enforcement**: 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. +##### Enforcement + +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. ### C.82: Don't call virtual functions in constructors and destructors -**Reason**: The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class. +##### Reason + + The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class. This can be most confusing. Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior. -**Example; bad**: +##### Example, bad class base { public: @@ -4338,12 +4837,13 @@ Note that calling a specific explicitly qualified function is not a virtual call **See also** [factory functions](#Rc-factory) for how to achieve the effect of a call to a derived class function without risking undefined behavior. - ### C.83: For value-like types, consider providing a `noexcept` swap function -**Reason**: 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). +##### Reason -**Example; good**: + 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). + +##### Example, good class Foo { // ... @@ -4365,15 +4865,18 @@ Providing a nonmember `swap` function in the same namespace as your type for cal a.swap(b); } -**Enforcement**: +##### Enforcement + * (Simple) A class without virtual functions should have a `swap` member function declared. * (Simple) When a class has a `swap` member function, it should be declared `noexcept`. ### C.84: A `swap` function may not fail -**Reason**: `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. +##### Reason -**Example, bad**: + `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. + +##### Example, bad void swap(My_vector& x, My_vector& y) { @@ -4384,23 +4887,29 @@ Providing a nonmember `swap` function in the same namespace as your type for cal 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. -**Enforcement**: (Simple) When a class has a `swap` member function, it should be declared `noexcept`. +##### Enforcement +(Simple) When a class has a `swap` member function, it should be declared `noexcept`. ### C.85: Make `swap` `noexcept` -**Reason**: [A `swap` may not fail](#Rc-swap-fail). +##### Reason + + [A `swap` may not fail](#Rc-swap-fail). If a `swap` tries to exit with an exception, it's a bad design error and the program had better terminate. -**Enforcement**: (Simple) When a class has a `swap` member function, it should be declared `noexcept`. +##### Enforcement +(Simple) When a class has a `swap` member function, it should be declared `noexcept`. ### C.86: Make `==` symmetric with respect to operand types and `noexcept` -**Reason**: Assymetric treatment of operands is surprising and a source of errors where conversions are possible. +##### Reason + + Assymetric treatment of operands is surprising and a source of errors where conversions are possible. `==` is a fundamental operations and programmers should be able to use it without fear of failure. -**Example**: +##### Example class X { string name; @@ -4409,7 +4918,7 @@ If a `swap` tries to exit with an exception, it's a bad design error and the pro bool operator==(const X& a, const X& b) noexcept { return a.name==b.name && a.number==b.number; } -**Example, bad**: +##### Example, bad class B { string name; @@ -4420,17 +4929,22 @@ If a `swap` tries to exit with an exception, it's a bad design error and the pro `B`'s comparison accepts conversions for its second operand, but not its first. -**Note**: If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw. +##### Note + +If a class has a failure state, like `double`'s `NaN`, there is a temptation to make a comparison against the failure state throw. The alternative is to make two failure states compare equal and any valid state compare false against the failure state. -**Enforcement**: ??? +##### Enforcement +??? ### C.87: Beware of `==` on base classes -**Reason**: It is really hard to write a foolproof and useful `==` for a hierarchy. +##### Reason -**Example, bad**: + It is really hard to write a foolproof and useful `==` for a hierarchy. + +##### Example, bad class B { string name; @@ -4458,29 +4972,37 @@ The alternative is to make two failure states compare equal and any valid state Of course there are way of making `==` work in a hierarchy, but the naive approaches do not scale -**Enforcement**: ??? +##### Enforcement +??? ### C.88: Make `<` symmetric with respect to operand types and `noexcept` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### C.89: Make a `hash` `noexcept` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement + +??? ## C.con: Containers and other resource handles @@ -4500,7 +5022,6 @@ Summary of container rules: **See also**: [Resources](#S-resource) - ## C.lambdas: Function objects and lambdas A function object is an object supplying an overloaded `()` so that you can call it. @@ -4513,8 +5034,6 @@ Summary: * [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) * [ES.28: Use lambdas for complex initialization, especially of `const` variables](#Res-lambda-init) - - ## C.hier: Class hierarchies (OOP) A class hierarchy is constructed to represent a set of hierarchically organized concepts (only). @@ -4555,18 +5074,20 @@ Accessing objects in a hierarchy rule summary: * [C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s](#Rh-make_shared) * [C.152: Never assign a pointer to an array of derived class objects to a pointer to its base](#Rh-array) - ### C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only) -**Reason**: 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. +##### Reason + + 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. 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. -**Example**: +##### Example ??? Good old Shape example? -**Example, bad**: +##### Example, bad + Do *not* represent non-hierarchical domain concepts as class hierarchies. template @@ -4593,61 +5114,68 @@ it may throw an exception instead. Thus users have to resort to run-time checking and/or not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a `dynamic_cast`). -**Enforcement**: +##### Enforcement * Look for classes with lots of members that do nothing but throw. * Flag every use of a nonpublic base class where the derived class does not override a virtual function or access a protected base member. - ### C.121: If a base class is used as an interface, make it a pure abstract class -**Reason**: A class is more stable (less brittle) if it does not contain data. Interfaces should normally be composed entirely of public pure virtual functions. +##### Reason -**Example**: + A class is more stable (less brittle) if it does not contain data. Interfaces should normally be composed entirely of public pure virtual functions. + +##### Example ??? -**Enforcement**: +##### Enforcement * Warn on any class that contains data members and also has an overridable (non-`final`) virtual function. - ### C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed -**Reason**: Such as on an ABI (link) boundary. +##### Reason -**Example**: + Such as on an ABI (link) boundary. + +##### Example ??? -**Enforcement**: ??? - +##### Enforcement +??? ## C.hierclass: Designing classes in a hierarchy: - ### C.126: An abstract class typically doesn't need a constructor -**Reason**: An abstract class typically does not have any data for a constructor to initialize. +##### Reason -**Example**: + An abstract class typically does not have any data for a constructor to initialize. + +##### Example ??? -**Exceptions**: +##### Exceptions + * A base class constructor that does work, such as registering an object somewhere, may need a constructor. * In extremely rare cases, you might find a reasonable for an abstract class to have a bit of data shared by all derived classes (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. -**Enforcement**: Flag abstract classes with constructors. +##### Enforcement +Flag abstract classes with constructors. ### C.127: A class with a virtual function should have a virtual destructor -**Reason**: 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. +##### Reason -**Example, bad**: + 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. + +##### Example, bad struct B { // ... no destructor ... @@ -4663,19 +5191,22 @@ not using this (over)general interface in favor of a particular interface found delete p; // leak the string } -**Note**: There are people who don't follow this rule because they plan to use a class only through a `shared_ptr`: `std::shared_ptr p = std::make_shared(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`. +##### Note -**Enforcement**: +There are people who don't follow this rule because they plan to use a class only through a `shared_ptr`: `std::shared_ptr p = std::make_shared(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`. + +##### Enforcement * 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. * Flag `delete` of a class with a virtual function but no virtual destructor. - ### C.128: Use `override` to make overriding explicit in large class hierarchies -**Reason**: Readability. Detection of mistakes. Explicit `override` allows the compiler to catch mismatch of types and/or names between base and derived classes. +##### Reason -**Example, bad**: + Readability. Detection of mistakes. Explicit `override` allows the compiler to catch mismatch of types and/or names between base and derived classes. + +##### Example, bad struct B { void f1(int); @@ -4691,28 +5222,32 @@ not using this (over)general interface in favor of a particular interface found // ... }; -**Enforcement**: +##### Enforcement * Compare names in base and derived classes and flag uses of the same name that does not override. * Flag overrides without `override`. - ### C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance -**Reason**: ??? Herb: I've become a non-fan of implementation inheritance -- seems most often an antipattern. Are there reasonable examples of it? +##### Reason -**Example**: + ??? Herb: I've become a non-fan of implementation inheritance -- seems most often an antipattern. Are there reasonable examples of it? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead -**Reason**: 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). +##### Reason -**Example**: + 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). + +##### Example class base { public: @@ -4726,17 +5261,18 @@ not using this (over)general interface in favor of a particular interface found Note that because of language rules, the covariant return type cannot be a smart pointer. -**Enforcement**: +##### Enforcement * Flag a class with a virtual function and a non-user-defined copy operation. * Flag an assignment of base class objects (objects of a class from which another has been derived). - ### C.131: Avoid trivial getters and setters -**Reason**: A trivial getter or setter adds no semantic value; the data item could just as well be `public`. +##### Reason -**Example**: + A trivial getter or setter adds no semantic value; the data item could just as well be `public`. + +##### Example class point { int x; @@ -4757,18 +5293,23 @@ Consider making such a class a `struct` -- that is, a behaviorless bunch of vari int y = 0; }; -**Note**: 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). +##### Note -**Enforcement**: Flag multiple `get` and `set` member functions that simply access a member without additional semantics. +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). +##### Enforcement + +Flag multiple `get` and `set` member functions that simply access a member without additional semantics. ### C.132: Don't make a function `virtual` without reason -**Reason**: Redundant `virtual` increases run-time and object-code size. +##### Reason + + Redundant `virtual` increases run-time and object-code size. A virtual function can be overridden and is thus open to mistakes in a derived class. A virtual function ensures code replication in a templated hierarchy. -**Example, bad**: +##### Example, bad template class Vector { @@ -4782,96 +5323,123 @@ A virtual function ensures code replication in a templated hierarchy. This kind of "vector" isn't meant to be used as a base class at all. -**Enforcement**: +##### Enforcement * Flag a class with virtual functions but no derived classes. * Flag a class where all member functions are virtual and have implementations. - ### C.133: Avoid `protected` data -**Reason**: `protected` data is a source of complexity and errors. +##### Reason + + `protected` data is a source of complexity and errors. `protected` data complicated the statement of invariants. `protected` data inherently violates the guidance against putting data in base classes, which usually leads to having to deal virtual inheritance as well. -**Example**: +##### Example ??? -**Note**: Protected member function can be just fine. +##### Note -**Enforcement**: Flag classes with `protected` data. +Protected member function can be just fine. +##### Enforcement + +Flag classes with `protected` data. ### C.134: Ensure all data members have the same access level -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example ??? -**Enforcement**: Flag any class that has data members with different access levels. +##### Enforcement +Flag any class that has data members with different access levels. ### C.135: Use multiple inheritance to represent multiple distinct interfaces -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example ??? -**Note**: This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common +##### Note + +This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common and such interfaces are often not easily or naturally organized into a single-rooted hierarchy. -**Note**: Such interfaces are typically abstract classes. +##### Note -**Enforcement**: ??? +Such interfaces are typically abstract classes. +##### Enforcement + +??? ### C.136: Use multiple inheritance to represent the union of implementation attributes -**Reason**: ??? 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? +##### Reason -**Example**: + ??? 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? + +##### Example ??? -**Note**: This a relatively rare use because implementation can often be organized into a single-rooted hierarchy. +##### Note -**Enforcement**: ??? Herb: How about opposite enforcement: Flag any type that inherits from more than one non-empty base class? +This a relatively rare use because implementation can often be organized into a single-rooted hierarchy. +##### Enforcement + +??? Herb: How about opposite enforcement: Flag any type that inherits from more than one non-empty base class? ### C.137: Use `virtual` bases to avoid overly general base classes -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Note**: ??? +##### Note -**Enforcement**: ??? +??? + +##### Enforcement + +??? ### C.138: Create an overload set for a derived class and its bases with `using` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? - ## C.hier-access: Accessing objects in a hierarchy - ### C.145: Access polymorphic objects through pointers and references -**Reason**: If you have a class with a virtual function, you don't (in general) know which class provided the function to be used. +##### Reason -**Example**: + If you have a class with a virtual function, you don't (in general) know which class provided the function to be used. + +##### Example struct B { int a; virtual int f(); }; struct D : B { int b; int f() override; }; @@ -4891,7 +5459,9 @@ and such interfaces are often not easily or naturally organized into a single-ro Both `d`s are sliced. -**Exception**: You can safely access a named polymorphic object in the scope of its definition, just don't slice it. +##### Exception + +You can safely access a named polymorphic object in the scope of its definition, just don't slice it. void use3() { @@ -4899,14 +5469,17 @@ Both `d`s are sliced. d.f(); // OK } -**Enforcement**: Flag all slicing. +##### Enforcement +Flag all slicing. ### C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable -**Reason**: `dynamic_cast` is checked at run time. +##### Reason -**Example**: + `dynamic_cast` is checked at run time. + +##### Example struct B { // an interface virtual void f(); @@ -4928,47 +5501,60 @@ Both `d`s are sliced. } } -**Note**: Like other casts, `dynamic_cast` is overused. +##### Note + +Like other casts, `dynamic_cast` is overused. [Prefer virtual functions to casting](#???). Prefer [static polymorphism](#???) to hierarchy navigation where it is possible (no run-time resolution necessary) and reasonably convenient. -**Exception**: If your implementation provided a really slow `dynamic_cast`, you may have to use a workaround. +##### Exception + +If your implementation provided a really slow `dynamic_cast`, you may have to use a workaround. However, all workarounds that cannot be statically resolved involve explicit casting (typically `static_cast`) and are error-prone. You will basically be crafting your own special-purpose `dynamic_cast`. 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) and that your use of `dynamic_cast` is really performance critical. -**Enforcement**: Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`. +##### Enforcement +Flag all uses of `static_cast` for downcasts, including C-style casts that perform a `static_cast`. ### C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new` -**Reason**: Avoid resource leaks. +##### Reason -**Example**: + Avoid resource leaks. + +##### Example void use(int i) { @@ -4978,50 +5564,53 @@ and that your use of `dynamic_cast` is really performance critical. delete p; // too late } -**Enforcement**: +##### Enforcement * Flag initialization of a naked pointer with the result of a `new` * Flag `delete` of local variable - ### C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s or other smart pointers -**Reason**: `make_unique` gives a more concise statement of the construction. +##### Reason -**Example**: + `make_unique` gives a more concise statement of the construction. + +##### Example unique_ptr p {new{7}); // OK: but repetitive auto q = make_unique(7); // Better: no repetition of Foo -**Enforcement**: +##### Enforcement * Flag the repetitive usage of template specialization list `` * Flag variables declared to be `unique_ptr` - ### C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s -**Reason**: `make_shared` gives a more concise statement of the construction. +##### Reason + + `make_shared` gives a more concise statement of the construction. 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. -**Example**: +##### Example shared_ptr p {new{7}); // OK: but repetitive; and separate allocations for the Foo and shared_ptr's use count auto q = make_shared(7); // Better: no repetition of Foo; one object -**Enforcement**: +##### Enforcement * Flag the repetitive usage of template specialization list`` * Flag variables declared to be `shared_ptr` - ### C.152: Never assign a pointer to an array of derived class objects to a pointer to its base -**Reason**: Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption. +##### Reason -**Example**: + Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption. + +##### Example struct B { int x; }; struct D : B { int y; }; @@ -5034,12 +5623,11 @@ It also gives an opportunity to eliminate a separate allocation for the referenc use(a); // bad: a decays to &a[0] which is converted to a B* -**Enforcement**: +##### Enforcement * Flag all combinations of array decay and base to derived conversions. * 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` - # C.over: Overloading and overloaded operators You can overload ordinary functions, template functions, and operators. @@ -5056,34 +5644,44 @@ Overload rule summary: ### C.140: Define operators primarily to mimic conventional usage -**Reason**: Minimize surprises. +##### Reason -**Example, bad**: + Minimize surprises. + +##### Example, bad X operator+(X a, X b) { return a.v-b.v; } // bad: makes + subtract ???. Non-member operators: namespace-level definition (traditional?) vs friend definition (as used by boost.operator, limits lookup to ADL only) -**Enforcement**: Possibly impossible. +##### Enforcement +Possibly impossible. ### C.141: Use nonmember functions for symmetric operators -**Reason**: If you use member functions, you need two. +##### Reason + + If you use member functions, you need two. Unless you use a non-member function for (say) `==`, `a==b` and `b==a` will be subtly different. -**Example**: +##### Example bool operator==(Point a, Point b) { return a.x==b.x && a.y==b.y; } -**Enforcement**: Flag member operator functions. +##### Enforcement +Flag member operator functions. ### C.142: Overload operations that are roughly equivalent -**Reason**: 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. +##### Reason -**Example**: Consider + 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. + +##### Example + +Consider void print(int a); void print(int a, int base); @@ -5097,14 +5695,19 @@ These three functions all prints their arguments (appropriately). Conversely These three functions all prints their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code. -**Enforcement**: ??? +##### Enforcement +??? ### C.143: Overload only for operations that are roughly equivalent -**Reason**: Having the same name for logically different functions is confusing and leads to errors when using generic programming. +##### Reason -**Example**: Consider + Having the same name for logically different functions is confusing and leads to errors when using generic programming. + +##### Example + +Consider void open_gate(Gate& g); // remove obstacle from garage exit lane void fopen(const char*name, const char* mode); // open file @@ -5117,21 +5720,28 @@ The two operations are fundamentally different (and unrelated) so it is good tha The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion. Fortunately, the type system will catch many such mistakes. -**Note**: be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`. +##### Note -**Enforcement**: ??? +be particularly careful about common and popular names, such as `open`, `move`, `+`, and `==`. +##### Enforcement + +??? ### C.144: Avoid conversion operators -**Reason**: Implicit conversions can be essential (e.g., `double` to '`int`) but often cause surprises (e.g., `String` to C-style string). +##### Reason -**Note**: Prefer explicitly named conversions until a serious need is demonstrated. + Implicit conversions can be essential (e.g., `double` to '`int`) but often cause surprises (e.g., `String` to C-style string). + +##### Note + +Prefer explicitly named conversions until a serious need is demonstrated. By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion) and frequently needed. Do not introduce implicit conversions (through conversion operators or non-`explicit` constructors) just to gain a minor convenience. -**Example, bad**: +##### Example, bad class String { // handle ownership and access to a sequence of characters // ... @@ -5153,13 +5763,17 @@ just to gain a minor convenience. The string allocated for `s` and assigned to `p` is destroyed before it can be used. -**Enforcement**: Flag all conversion operators. +##### Enforcement + +Flag all conversion operators. ### C.170: If you feel like overloading a lambda, use a generic lambda -**Reason**: You can overload by defining two different lambdas with the same name +##### Reason -**Example**: + You can overload by defining two different lambdas with the same name + +##### Example void f(int); void f(double); @@ -5170,8 +5784,9 @@ The string allocated for `s` and assigned to `p` is destroyed before it can be u auto h = [](auto) { /* ... */ }; // OK -**Enforcement**: The compiler catches attempt to overload a lambda. +##### Enforcement +The compiler catches attempt to overload a lambda. ## C.union: Unions @@ -5184,48 +5799,54 @@ Union rule summary: * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous) * ??? - ### C.180: Use `union`s to ??? ??? When should unions be used, if at all? What's a good future-proof way to re-interpret object representations of PODs? ??? variant -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### C.181: Avoid "naked" `union`s -**Reason**: Naked unions are a source of type errors. +##### Reason + + Naked unions are a source of type errors. **Alternative**: Wrap them in a class together with a type field. **Alternative**: Use `variant`. -**Example**: +##### Example ??? -**Enforcement**: ??? - +##### Enforcement +??? ### C.182: Use anonymous `union`s to implement tagged unions -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? - +##### Enforcement +??? # Enum: Enumerations @@ -5241,73 +5862,89 @@ Enumeration rule summary: * [Enum.6: Use unnamed enumerations for ???](#Renum-unnamed) * ??? - ### Enum.1: Prefer enums over macros -**Reason**: Macros do not obey scope and type rules. +##### Reason -**Example**: + Macros do not obey scope and type rules. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Enum.2: Use enumerations to represent sets of named constants -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Enum.3: Prefer class enums over ``plain'' enums -**Reason**: to minimize surprises +##### Reason -**Example**: + to minimize surprises + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Enum.4: Define operations on enumerations for safe and simple use -**Reason**: Convenience of us and avoidance of errors. +##### Reason -**Example**: + Convenience of us and avoidance of errors. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Enum.5: Don't use ALL_CAPS for enumerators -**Reason**: Avoid clashes with macros +##### Reason -**Example**: + Avoid clashes with macros + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Enum.6: Use unnamed enumerations for ??? -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? - +##### Enforcement +??? # R: Resource management @@ -5358,12 +5995,16 @@ Here, we ignore such cases. ### Rule R.1: Manage resources automatically using resource handles and RAII (resource acquisition is initialization) -**Reason**: To avoid leaks and the complexity of manual resource management. +##### Reason + + To avoid leaks and the complexity of manual resource management. 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`. 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. -**Example, bad**: Consider +##### Example, bad + + Consider void send( X* x, cstring_view destination ) { auto port = OpenPort(destination); @@ -5379,7 +6020,9 @@ Here, we ignore such cases. In this code, you have to remember to `unlock`, `ClosePort`, and `delete` on all paths, and do each exactly once. Further, if any of the code marked `...` throws an exception, then `x` is leaked and `my_mutex` remains locked. -**Example**: Consider +##### Example + +Consider void send( unique_ptr x, cstring_view destination ) { // x owns the X Port port{destination}; // port owns the PortHandle @@ -5405,17 +6048,20 @@ What is `Port`? A handy wrapper that encapsulates the resource: Port& operator=(const Port&) =delete; }; -**Note**: 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) +##### Note + +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) **See also**: [RAII](#Rr-raii). - ### R.2: In interfaces, use raw pointers to denote individual objects (only) -**Reason**: Arrays are best represented by a container type (e.g., `vector` (owning)) or an `array_view` (non-owning). +##### Reason + + Arrays are best represented by a container type (e.g., `vector` (owning)) or an `array_view` (non-owning). Such containers and views hold sufficient information to do range checking. -**Example, bad**: +##### Example, bad void f(int* p, int n) // n is the number of elements in p[] { @@ -5427,7 +6073,7 @@ Such containers and views hold sufficient information to do range checking. The compiler does not read comments, and without reading other code you do not know whether `p` really points to `n` elements. Use an `array_view` instead. -**Example**: +##### Example void g(int* p, int fmt) // print *p using format #fmt { @@ -5437,23 +6083,25 @@ Use an `array_view` instead. **Exception**: C-style strings are passed as single pointers to a zero-terminated sequence of characters. Use `zstring` rather than `char*` to indicate that you rely on that convention. -**Note**: Many current uses of pointers to a single element could be references. +##### Note + +Many current uses of pointers to a single element could be references. However, where `nullptr` is a possible value, a reference may not be an reasonable alternative. -**Enforcement**: +##### Enforcement * Flag pointer arithmetic (including `++`) on a pointer that is not part of a container, view, or iterator. This rule would generate a huge number of false positives if applied to an older code base. * Flag array names passed as simple pointers - - ### R.3: A raw pointer (a `T*`) is non-owning -**Reason**: There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning. +##### Reason + + There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning. We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers. -**Example**: +##### Example void f() { @@ -5464,7 +6112,7 @@ We want owning pointers identified so that we can reliably and efficiently delet The `unique_ptr` protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The `T*` does not. -**Example**: +##### Example template class X { @@ -5484,16 +6132,21 @@ We can fix that problem by making ownership explicit: T* q; // OK: q is not owning }; -**Note**: The fact that there are billions of lines of code that violates this rule against owning `T*`s cannot be ignored. +##### Note + +The fact that there are billions of lines of code that violates this rule against owning `T*`s cannot be ignored. This code cannot all be rewritten (ever assuming good code transformation software). 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. Also, many ABIs (and essentially all interfaces to C code) use `T*`s, some of them owning. -**Note**: `owner` has no default semantics beyond `T*` it can be used without changing any code using it and without affecting ABIs. +##### Note + +`owner` has no default semantics beyond `T*` it can be used without changing any code using it and without affecting ABIs. It is simply a (most valuable) indicator to programmers and analysis tools. For example, if an `owner` is a member of a class, that class better have a destructor that `delete`s it. -**Example**, bad: +##### Example, bad + Returning a (raw) pointer imposes a life-time management burden on the caller; that is, who deletes the pointed-to object? Gadget* make_gadget(int n) @@ -5521,12 +6174,16 @@ just return it "by value:' return g; } -**Note**: This rule applies to factory functions. +##### Note -**Note**: If pointer semantics is required (e.g., because the return type needs to refer to a base class of a class hierarchy (an interface)), +This rule applies to factory functions. + +##### Note + +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." -**Enforcement**: +##### Enforcement * (Simple) Warn on `delete` of a raw pointer that is not an `owner`. * (Moderate) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path. @@ -5536,10 +6193,12 @@ return a "smart pointer." ### R.4: A raw reference (a `T&`) is non-owning -**Reason**: There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning. +##### Reason + + There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning. We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers. -**Example**: +##### Example void f() { @@ -5550,16 +6209,21 @@ We want owners identified so that we can reliably and efficiently delete the obj **See also**: [The raw pointer rule](#Rr-ptr) -**Enforcement**: See [the raw pointer rule](#Rr-ptr) +##### Enforcement +See [the raw pointer rule](#Rr-ptr) ### R.5: Prefer scoped objects -**Reason**: A scoped object is a local object, a global object, or a member. +##### Reason + + A scoped object is a local object, a global object, or a member. This implies that there is no separate allocation and deallocation cost in excess that already used for the containing scope or object. The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes. -**Example**: 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: +##### Example + +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: void some_function(int n) { @@ -5576,16 +6240,16 @@ Instead, use a local variable: // ... } -**Enforcement**: +##### Enforcement * (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. * (Simple) Warn if a local `Unique_ptr` or `Shared_ptr` is not moved, copied, reassigned or `reset` before its lifetime ends. - - ### R.6: Avoid non-`const` global variables -**Reason**: Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects. +##### Reason + + Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects. They are a notable source of errors. **Warning**: The initialization of global objects is not totally ordered. If you use a global object initialize it with a constant. @@ -5594,17 +6258,19 @@ They are a notable source of errors. **Exception**: An immutable (`const`) global does not introduce the problems we try to avoid by banning global objects. -**Enforcement**: (??? NM: Obviously we can warn about non-const statics....do we want to?) +##### Enforcement +(??? NM: Obviously we can warn about non-const statics....do we want to?) ## R.alloc: Allocation and deallocation - ### R.10: Avoid `malloc()` and `free()` -**Reason**: `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`. +##### Reason -**Example**: + `malloc()` and `free()` do not support construction and destruction, and do not mix well with `new` and `delete`. + +##### Example class Record { int id; @@ -5632,33 +6298,43 @@ They are a notable source of errors. In some implementations that `delete` and that `free()` might work, or maybe they will cause run-time errors. -**Exception**: There are applications and sections of code where exceptions are not acceptable. +##### Exception + +There are applications and sections of code where exceptions are not acceptable. Some of the best such example are in life-critical hard real-time code. Beware that many bans on exception use are based on superstition (bad) or by concerns for older code bases with unsystematics resource management (unfortunately, but sometimes necessary). In such cases, consider the `nothrow` versions of `new`. -**Enforcement**: Flag explicit use of `malloc` and `free`. +##### Enforcement +Flag explicit use of `malloc` and `free`. ### R.11: Avoid calling `new` and `delete` explicitly -**Reason**: The pointer returned by `new` should belong to a resource handle (that can call `delete`). +##### Reason + + The pointer returned by `new` should belong to a resource handle (that can call `delete`). If the pointer returned from `new` is assigned to a plain/naked pointer, the object can be leaked. -**Note**: In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management) +##### Note + +In a large program, a naked `delete` (that is a `delete` in application code, rather than part of code devoted to resource management) 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? The bug may be latent: it may emerge only during maintenance. If you have a naked `new`, you probably need a naked `delete` somewhere, so you probably have a bug. -**Enforcement**: (Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead. +##### Enforcement +(Simple) Warn on any explicit use of `new` and `delete`. Suggest using `make_unique` instead. ### R.12: Immediately give the result of an explicit resource allocation to a manager object -**Reason**: If you don't, an exception or a return may lead to a leak. +##### Reason -**Example, bad**: + If you don't, an exception or a return may lead to a leak. + +##### Example, bad void f(const string& name) { @@ -5670,7 +6346,7 @@ If you have a naked `new`, you probably need a naked `delete` somewhere, so you The allocation of `buf` may fail and leak the file handle. -**Example**: +##### Example void f(const string& name) { @@ -5681,17 +6357,18 @@ The allocation of `buf` may fail and leak the file handle. The use of the file handle (in `ifstream`) is simple, efficient, and safe. -**Enforcement**: +##### Enforcement * Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?) - ### R.13: Perform at most one explicit resource allocation in a single expression statement -**Reason**: If you perform two explicit resource allocations in one statement, +##### Reason + + 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. -**Example**: +##### Example void fun( shared_ptr sp1, shared_ptr sp2 ); @@ -5716,29 +6393,33 @@ The best solution is to avoid explicit allocation entirely use factory functions Write your own factory wrapper if there is not one already. -**Enforcement**: +##### Enforcement * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?) - ### R.14: ??? array vs. pointer parameter -**Reason**: An array decays to a pointer, thereby losing its size, opening the opportunity for range errors. +##### Reason -**Example**: + An array decays to a pointer, thereby losing its size, opening the opportunity for range errors. + +##### Example ??? what do we recommend: f(int*[]) or f(int**) ??? **Alternative**: Use `array_view` to preserve size information. -**Enforcement**: Flag `[]` parameters. +##### Enforcement +Flag `[]` parameters. ### R.15: Always overload matched allocation/deallocation pairs -**Reason**. Otherwise you get mismatched operations and chaos. +##### Reason -**Example**: +Otherwise you get mismatched operations and chaos. + +##### Example class X { // ... @@ -5747,20 +6428,26 @@ Write your own factory wrapper if there is not one already. // ... }; -**Note**: If you want memory that cannot be deallocated, `=delete` the deallocation operation. +##### Note + +If you want memory that cannot be deallocated, `=delete` the deallocation operation. Don't leave it undeclared. -**Enforcement**: Flag incomplete pairs. +##### Enforcement +Flag incomplete pairs. ## R.smart: Smart pointers - ### Rule R.20: Use `unique_ptr` or `shared_ptr` to represent ownership -**Reason**: They can prevent resource leaks. +##### Reason -**Example**: Consider + They can prevent resource leaks. + +##### Example + +Consider void f() { @@ -5772,14 +6459,19 @@ Don't leave it undeclared. This will leak the object used to initialize `p1` (only). -**Enforcement**: (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer. +##### Enforcement +(Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer. ### Rule R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership -**Reason**: a `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count). +##### Reason -**Example, bad**: This needlessly adds and maintains a reference count + a `unique_ptr` is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count). + +##### Example, bad + + This needlessly adds and maintains a reference count void f() { @@ -5787,7 +6479,9 @@ This will leak the object used to initialize `p1` (only). // use base locally, without copying it -- refcount never exceeds 1 } // destroy base -**Example**: This is more efficient +##### Example + +This is more efficient void f() { @@ -5795,58 +6489,73 @@ This will leak the object used to initialize `p1` (only). // use base locally } // destroy base +##### Enforcement -**Enforcement**: (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. - +(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. ### R.22: Use `make_shared()` to make `shared_ptr`s -**Reason**: 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. +##### Reason -**Example**: Consider + 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. + +##### Example + +Consider shared_ptr p1 { new X{2} }; // bad auto p = make_shared(2); // good The `make_shared()` version mentions `X` only once, so it is usually shorter (as well as faster) than the version with the explicit `new`. -**Enforcement**: (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`. +##### Enforcement +(Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`. ### Rule R.23: Use `make_unique()` to make `unique_ptr`s -**Reason**: for convenience and consistency with `shared_ptr`. +##### Reason -**Note**: `make_unique()` is C++14, but widely available (as well as simple to write). + for convenience and consistency with `shared_ptr`. -**Enforcement**: (Simple) Warn if a `Shared_ptr` is constructed from the result of `new` rather than `make_unique`. +##### Note +`make_unique()` is C++14, but widely available (as well as simple to write). + +##### Enforcement + +(Simple) Warn if a `Shared_ptr` is constructed from the result of `new` rather than `make_unique`. ### R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s -**Reason**: `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 +##### Reason + + `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 be able to destroy a cyclic structure. -**Example**: +##### Example ??? -**Note**: ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.) +##### Note + + ??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.) ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it. You could "temporarily share ownership simply by using another `stared_ptr`.) -**Enforcement**: ???probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr` - - +##### Enforcement +???probably impossible. If we could statically detect cycles, we wouldn't need `weak_ptr` ### R.30: Take smart pointers as parameters only to explicitly express lifetime semantics -**Reason**: Accepting a smart pointer to a `widget` is wrong if the function just needs the `widget` itself. +##### Reason + + Accepting a smart pointer to a `widget` is wrong if the function just needs the `widget` itself. It should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer. A function that does not manipulate lifetime should take raw pointers or references instead. -**Example; bad**: +##### Example, bad // callee void f( shared_ptr& w ) { @@ -5862,7 +6571,7 @@ A function that does not manipulate lifetime should take raw pointers or referen widget stack_widget; f( stack_widget ); // error -**Example; good**: +##### Example, good // callee void f( widget& w ) { @@ -5878,14 +6587,16 @@ A function that does not manipulate lifetime should take raw pointers or referen widget stack_widget; f( stack_widget ); // ok -- now this works -**Enforcement**: +##### Enforcement * (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()`). Suggest using a `T*` or `T&` instead. ### R.31: If you have non-`std` smart pointers, follow the basic pattern from `std` -**Reason**: 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. +##### Reason + + 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. You want the rules to work on all the smart pointers you use. Any type (including primary template or specialization) that overloads unary `*` and `->` is considered a smart pointer: @@ -5893,7 +6604,7 @@ Any type (including primary template or specialization) that overloads unary `*` * If it is copyable, it is recognized as a reference-counted `Shared_ptr`. * If it not copyable, it is recognized as a unique `Unique_ptr`. -**Example**: +##### Example // use Boost's intrusive_ptr #include @@ -5915,53 +6626,57 @@ so these guideline enforcement rules work on them out of the box and expose this ### R.32: Take a `unique_ptr` parameter to express that a function assumes ownership of a `widget` -**Reason**: Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer. +##### Reason -**Example**: + Using `unique_ptr` in this way both documents and enforces the function call's ownership transfer. + +##### Example void sink(unique_ptr); // consumes the widget void sink(widget*); // just uses the widget -**Example; bad**: +##### Example, bad void thinko(const unique_ptr&); // usually not what you want - -**Enforcement**: +##### Enforcement * (Simple) Warn if a function takes a `Unique_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr` parameter by reference to `const`. Suggest taking a `const T*` or `const T&` instead. * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr` parameter by rvalue reference. Suggest using pass by value instead. - ### R.33: Take a `unique_ptr&` parameter to express that a function reseats the`widget` -**Reason**: Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics. +##### Reason -**Note**: "reseat" means "making a reference or a smart pointer refer to a different object." + Using `unique_ptr` in this way both documents and enforces the function call's reseating semantics. -**Example**: +##### Note + +"reseat" means "making a reference or a smart pointer refer to a different object." + +##### Example void reseat( unique_ptr& ); // "will" or "might" reseat pointer -**Example; bad**: +##### Example, bad void thinko( const unique_ptr& ); // usually not what you want - -**Enforcement**: +##### Enforcement * (Simple) Warn if a function takes a `Unique_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr` parameter by reference to `const`. Suggest taking a `const T*` or `const T&` instead. * (Simple) ((Foundation)) Warn if a function takes a `Unique_ptr` parameter by rvalue reference. Suggest using pass by value instead. - ### R.34: Take a `shared_ptr` parameter to express that a function is part owner -**Reason**: This makes the function's ownership sharing explicit. +##### Reason -**Example; good**: + This makes the function's ownership sharing explicit. + +##### Example, good void share( shared_ptr ); // share – "will" retain refcount @@ -5969,20 +6684,23 @@ so these guideline enforcement rules work on them out of the box and expose this void may_share( const shared_ptr& ); // "might" retain refcount -**Enforcement**: +##### Enforcement * (Simple) Warn if a function takes a `Shared_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr` by rvalue reference. Suggesting taking it by value instead. - ### R.35: Take a `shared_ptr&` parameter to express that a function might reseat the shared pointer -**Reason**: This makes the function's reseating explicit. +##### Reason -**Note**: "reseat" means "making a reference or a smart pointer refer to a different object." + This makes the function's reseating explicit. -**Example; good**: +##### Note + +"reseat" means "making a reference or a smart pointer refer to a different object." + +##### Example, good void share( shared_ptr ); // share – "will" retain refcount @@ -5990,18 +6708,19 @@ so these guideline enforcement rules work on them out of the box and expose this void may_share( const shared_ptr& ); // "might" retain refcount -**Enforcement**: +##### Enforcement * (Simple) Warn if a function takes a `Shared_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr` by rvalue reference. Suggesting taking it by value instead. - ### R.36: Take a `const shared_ptr&` parameter to express that it might retain a reference count to the object ??? -**Reason**: This makes the function's ??? explicit. +##### Reason -**Example; good**: + This makes the function's ??? explicit. + +##### Example, good void share( shared_ptr ); // share – "will" retain refcount @@ -6009,23 +6728,28 @@ so these guideline enforcement rules work on them out of the box and expose this void may_share( const shared_ptr& ); // "might" retain refcount -**Enforcement**: +##### Enforcement * (Simple) Warn if a function takes a `Shared_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr` 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. * (Simple) ((Foundation)) Warn if a function takes a `Shared_ptr` by rvalue reference. Suggesting taking it by value instead. - ### R.37: Do not pass a pointer or reference obtained from an aliased smart pointer -**Reason**: Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer. +##### Reason + + Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer. Functions should prefer to pass raw pointers and references down call chains. At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive. You need to be sure that smart pointer cannot be inadvertently be reset or reassigned from within the call tree below -**Note**: 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. +##### Note -**Example**: Consider this code: +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. + +##### Example + +Consider this code: // global (static or heap), or aliased local... shared_ptr g_p = ...; @@ -6055,13 +6779,10 @@ The fix is simple -- take a local copy of the pointer to "keep a ref count" for pin->func(); // GOOD: same reason } -**Enforcement**: +##### Enforcement * (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. - - - # ES: Expressions and Statements Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements. @@ -6073,7 +6794,6 @@ General rules: * [ES.1: Prefer the standard library to other libraries and to "handcrafted code"](#Res-lib) * [ES.2: Prefer suitable abstractions to direct use of language features](#Res-abstr) - Declaration rules: * [ES.5: Keep scopes small](#Res-scope) @@ -6097,7 +6817,6 @@ Declaration rules: * [ES.32: Use `ALL_CAPS` for all macro names](#Res-CAPS!) * [ES.40: Don't define a (C-style) variadic function](#Res-ellipses) - Expression rules: * [ES.40: Avoid complicated expressions](#Res-complicated) @@ -6116,8 +6835,6 @@ Expression rules: * [ES.61: delete arrays using `delete[]` and non-arrays using `delete`](#Res-del) * [ES.62: Don't compare pointers into different arrays](#Res-arr2) - - Statement rules: * [ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice](#Res-switch-if) @@ -6141,14 +6858,15 @@ Arithmetic rules: * [ES.104: Don't underflow](#Res-overflow) * [ES.105: Don't divide by zero](#Res-zero) - ### ES.1: Prefer the standard library to other libraries and to "handcrafted code" -**Reason**: 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. +##### Reason + + 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. The ISO C++ standard library is among the most widely know and best tested libraries. It is available as part of all C++ Implementations. -**Example**: +##### Example auto sum = accumulate(begin(a), end(a), 0.0); // good @@ -6165,15 +6883,17 @@ but don't hand-code a well-known algorithm **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. -**Enforcement**: Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity? +##### Enforcement +Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity? ### ES.2: Prefer suitable abstractions to direct use of language features -**Reason**: 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. +##### Reason + 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. -**Example**: +##### Example vector read1(istream& is) // good { @@ -6200,21 +6920,23 @@ The more traditional and lower-level near-equivalent is longer, messier, harder 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. -**Enforcement**: Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity? +##### Enforcement +Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity? ## ES.dcl: Declarations A declaration is a statement. a declaration introduces a name into a scope and may cause the construction of a named object. - ### ES.5: Keep scopes small -**Reason**: Readability. Minimize resource retention. Avoid accidental misuse of value. +##### Reason + + Readability. Minimize resource retention. Avoid accidental misuse of value. **Alternative formulation**: Don't declare a name in an unnecessarily large scope. -**Example**: +##### Example void use() { @@ -6231,7 +6953,7 @@ A declaration is a statement. a declaration introduces a name into a scope and m } } -**Example, bad**: +##### Example, bad void use(const string& name) { @@ -6263,17 +6985,18 @@ In this case, it might be a good ide to factor out the read: 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`. -**Enforcement**: +##### Enforcement * Flag loop variable declared outside a loop and not used after the loop * Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N) - ### ES.6: Declare names in for-statement initializers and conditions to limit scope -**Reason**: Readability. Minimize resource retention. +##### Reason -**Example**: + Readability. Minimize resource retention. + +##### Example void use() { @@ -6292,17 +7015,20 @@ I am assuming that `Record` is large and doesn't have a good move operation so t } } -**Enforcement**: +##### Enforcement * Flag loop variables declared before the loop and not used after the loop * (hard) Flag loop variables declared before the loop and used after the loop for an unrelated purpose. - ### ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer -**Reason**: Readability. Lowering the chance of clashes between unrelated non-local names. +##### Reason -**Example**: Conventional short, local names increase readability: + Readability. Lowering the chance of clashes between unrelated non-local names. + +##### Example + +Conventional short, local names increase readability: template // good void print(ostream& os, const vector& v) @@ -6325,7 +7051,9 @@ An index is conventionally called `i` and there is no hint about the meaning of Yes, it is a caricature, but we have seen worse. -**Example**: Unconventional and short non-local names obscure code: +##### Example + +Unconventional and short non-local names obscure code: void use1(const string& s) { @@ -6334,7 +7062,6 @@ Yes, it is a caricature, but we have seen worse. // ... } - Better, give non-local entities readable names: void use1(const string& s) @@ -6346,7 +7073,9 @@ Better, give non-local entities readable names: Here, there is a chance that the reader knows what `trim_tail` means and that the reader can remember it after looking it up. -**Example, bad**: Argument names of large functions are de facto non-local and should be meaningful: +##### Example, bad + + Argument names of large functions are de facto non-local and should be meaningful: void complicated_algorithm(vector&vr, const vector& vi, map& out) // read from events in vr (marking used Records) for the indices in vi placing (name, index) pairs into out @@ -6356,25 +7085,31 @@ Here, there is a chance that the reader knows what `trim_tail` means and that th We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that. -**Enforcement**: Check length of local and non-local names. Also take function length into account. +##### Enforcement +Check length of local and non-local names. Also take function length into account. ### ES.8: Avoid similar-looking names -**Reason**: Such names slow down comprehension and increase the likelihood of error. +##### Reason -**Example**: + Such names slow down comprehension and increase the likelihood of error. + +##### Example if (readable(i1+l1+ol+o1+o0+ol+o1+I0+l0)) surprise(); -**Enforcement**: Check names against a list of known confusing letter and digit combinations. +##### Enforcement +Check names against a list of known confusing letter and digit combinations. ### ES.9: Avoid `ALL_CAPS` names -**Reason**: Such names are commonly used for macros. Thus, ALL_CAPS name are vulnerable to unintended macro substitution. +##### Reason -**Example**: + Such names are commonly used for macros. Thus, ALL_CAPS name are vulnerable to unintended macro substitution. + +##### Example // somewhere in some header: #define NE != @@ -6391,22 +7126,27 @@ We recommend keeping functions short, but that rule isn't universally adhered to // ... } -**Note**: Do not use `ALL_CAPS` for constants just because constants used to be macros. +##### Note -**Enforcement**: Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names. +Do not use `ALL_CAPS` for constants just because constants used to be macros. +##### Enforcement + +Flag all uses of ALL CAPS. For older code, accept ALL CAPS for macro names and flag all non-ALL-CAPS macro names. ### ES.10: Declare one name (only) per declaration -**Reason**: One-declaration-per line increases readability and avoid mistake related to the C/C++ grammar. It leaves room for a `//`-comment +##### Reason -**Example; bad**: + One-declaration-per line increases readability and avoid mistake related to the C/C++ grammar. It leaves room for a `//`-comment + +##### Example, bad char *p, c, a[7], *pp[7], **aa[10]; // yuck! **Exception**: a function declaration can contain several function argument declarations. -**Example**: +##### Example template bool any_of(InputIterator first, InputIterator last, Predicate pred); @@ -6415,7 +7155,7 @@ or better using concepts bool any_of(InputIterator first, InputIterator last, Predicate pred); -**Example**: +##### Example double scalbn(double x, int n); // OK: x*pow(FLT_RADIX, n); FLT_RADIX is usually 2 @@ -6430,18 +7170,21 @@ or double scalbn(double base, int exponent); // better: base*pow(FLT_RADIX, exponent); FLT_RADIX is usually 2 -**Enforcement**: Flag non-function arguments with multiple declarators involving declarator operators (e.g., `int* p, q;`) +##### Enforcement +Flag non-function arguments with multiple declarators involving declarator operators (e.g., `int* p, q;`) ### ES.11: Use `auto` to avoid redundant repetition of type names -**Reason**: +##### Reason * Simple repetition is tedious and error prone. * When you us `auto`, the name of the declared entity is in a fixed position in the declaration, increasing readability. * In a template function declaration the return type can be a member type. -**Example**: Consider +##### Example + +Consider auto p = v.begin(); // vector::iterator auto s = v.size(); @@ -6451,31 +7194,36 @@ or In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong. -**Example**: +##### Example template auto Container::first() -> Iterator; // Container::Iterator **Exception**: Avoid `auto` for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion. -**Example**: +##### Example auto lst = { 1, 2, 3 }; // lst is an initializer list (obviously) auto x{1}; // x is an int (after correction of the C++14 standard; initializer_list in C++11) -**Note**: When concepts become available, we can (and should) be more specific about the type we are deducing: +##### Note + +When concepts become available, we can (and should) be more specific about the type we are deducing: // ... ForwardIterator p = algo(x, y, z); -**Enforcement**: Flag redundant repetition of type names in a declaration. +##### Enforcement +Flag redundant repetition of type names in a declaration. ### ES.20: Always initialize an object -**Reason**: Avoid used-before-set errors and their associated undefined behavior. +##### Reason -**Example**: + Avoid used-before-set errors and their associated undefined behavior. + +##### Example void use(int arg) // bad: uninitialized variable { @@ -6493,7 +7241,9 @@ No, `i=7` does not initialize `i`; it assigns to it. Also, `i` can be read in th // ... } -**Exception**: It you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization. +##### Exception + +It you are declaring an object that is just about to be initialized from input, initializing it would cause a double initialization. However, beware that this may leave uninitialized data beyond the input - and that has been a fertile source of errors and security breaches: constexpr int max = 8*1024; @@ -6526,14 +7276,18 @@ In the not uncommon case where the input target and the input operation get sepa A good optimizer should know about input operations and eliminate the redundant operation. -**Exception**: Sometimes, we want to initialize a set of variables with a call to a function that returns several values. +##### Exception + +Sometimes, we want to initialize a set of variables with a call to a function that returns several values. That can lead to uninitialized variables (exceptly as for input operations): error_code ec; Value v; tie(ec, v) = get_value(); // get_value() returns a pair -**Note**: Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable. +##### Note + +Sometimes, a lambda can be used as an initializer to avoid an uninitialized variable. error_code ec; Value v = [&]() { @@ -6552,37 +7306,41 @@ or maybe **See also**: [ES.28](#Res-lambda-init) -**Enforcement**: +##### Enforcement * Flag every uninitialized variable. Don't flag variables of user-defined types with default constructors. * Check that the uninitialized buffer is read into *immediately* after declaration. - ### ES.21: Don't introduce a variable (or constant) before you need to use it -**Reason**: Readability. To limit the scope in which the variable can be used. +##### Reason -**Example**: + Readability. To limit the scope in which the variable can be used. + +##### Example int x = 7; // ... no use of x here ... ++x; -**Enforcement**: Flag declaration that distant from their first use. +##### Enforcement +Flag declaration that distant from their first use. ### ES.22: Don't declare a variable until you have a value to initialize it with -**Reason**: Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment. +##### Reason -**Example, bad**: + Readability. Limit the scope in which a variable can be used. Don't risk used-before-set. Initialization is often more efficient than assignment. + +##### Example, bad string s; // ... no use of s here ... s = "what a waste"; -**Example, bad**: +##### Example, bad SomeLargeType var; // ugly CaMeLcAsEvArIaBlE @@ -6605,34 +7363,41 @@ If not, we have a "use before set" bug. This is a maintenance trap. For initializers of moderate complexity, including for `const` variables, consider using a lambda to express the initializer; see [ES.28](#Res-lambda-init). -**Enforcement**: +##### Enforcement * Flag declarations with default initialization that are assigned to before they are first read. * Flag any complicated computation after an uninitialized variable and before its use. - ### ES.23: Prefer the `{}` initializer syntax -**Reason**: The rules for `{}` initialization is simpler, more general, and safer than for other forms of initialization, and unambiguous. +##### Reason -**Example**: + The rules for `{}` initialization is simpler, more general, and safer than for other forms of initialization, and unambiguous. + +##### Example int x {f(99)}; vector v = {1, 2, 3, 4, 5, 6}; -**Exception**: For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes: +##### Exception + +For containers, there is a tradition for using `{...}` for a list of elements and `(...)` for sizes: vector v1(10); // vector of 10 elements with the default value 0 vector v2 {10}; // vector of 1 element with the value 10 -**Note**: `{}`-initializers do not allow narrowing conversions. +##### Note -**Example**: +`{}`-initializers do not allow narrowing conversions. + +##### Example int x {7.9}; // error: narrowing int y = 7.9; // OK: y becomes 7. Hope for a compiler warning -**Note**: `{}` initialization can be used for all initialization; other forms of initialization can't: +##### Note + +`{}` initialization can be used for all initialization; other forms of initialization can't: auto p = new vector {1, 2, 3, 4, 5}; // initialized vector D::D(int a, int b) :m{a, b} { // member initializer (e.g., m might be a pair) @@ -6644,7 +7409,9 @@ For initializers of moderate complexity, including for `const` variables, consid // ... }; -**Note**: Initialization of a variable declared `auto` with a single value `{v}` surprising results until recently: +##### Note + +Initialization of a variable declared `auto` with a single value `{v}` surprising results until recently: auto x1 {7}; // x1 is sn int with the value 7 auto x2 = {7}; // x2 is and initializer_int with an element 7 @@ -6652,11 +7419,13 @@ For initializers of moderate complexity, including for `const` variables, consid auto x11 {7, 8}; // error: two initializers auto x22 = {7, 8}; // x2 is and initializer_int with elements 7 and 8 -**Exception**: Use `={...}` if you really want an `initializer_list` +##### Exception + +Use `={...}` if you really want an `initializer_list` auto fib10 = {0, 1, 2, 3, 5, 8, 13, 25, 38, 63}; // fib10 is a list -**Example**: +##### Example template void f() @@ -6671,17 +7440,20 @@ For initializers of moderate complexity, including for `const` variables, consid **See also**: [Discussion](#???) -**Enforcement**: Tricky. +##### Enforcement + +Tricky. * Don't flag uses of `=` for simple initializers. * Look for `=` after `auto` has been seen. - ### ES.24: Use a `unique_ptr` to hold pointers in code that may throw -**Reason**: Using `std::unique_ptr` is the simplest way to avoid leaks. And it is free compared to alternatives +##### Reason -**Example**: + Using `std::unique_ptr` is the simplest way to avoid leaks. And it is free compared to alternatives + +##### Example void use(bool leak) { @@ -6694,14 +7466,17 @@ For initializers of moderate complexity, including for `const` variables, consid If `leak==true` the object pointer to by `p2` is leaked and the object pointed to by `p1` is not. -**Enforcement**: Look for raw pointers that are targets of `new`, `malloc()`, or functions that may return such pointers. +##### Enforcement +Look for raw pointers that are targets of `new`, `malloc()`, or functions that may return such pointers. ### ES.25: Declare an objects `const` or `constexpr` unless you want to modify its value later on -**Reason**: That way you can't change the value by mistake. That way may offer the compiler optimization opportunities. +##### Reason -**Example**: + That way you can't change the value by mistake. That way may offer the compiler optimization opportunities. + +##### Example void f(int n) { @@ -6710,14 +7485,17 @@ If `leak==true` the object pointer to by `p2` is leaked and the object pointed t // ... } -**Enforcement**: 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. +##### Enforcement +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. ### ES.26: Don't use a variable for two unrelated purposes -**Reason**: Readability. +##### Reason -**Example, bad**: + Readability. + +##### Example, bad void use() { @@ -6726,15 +7504,18 @@ If `leak==true` the object pointer to by `p2` is leaked and the object pointed t for (i=0; i<200; ++i) { /* ... */ } // bad: i recycled } -**Enforcement**: Flag recycled variables. +##### Enforcement +Flag recycled variables. ### ES.27: Use `std::array` or `stack_array` for arrays on the stack -**Reason**: They are readable and don't implicitly convert to pointers. +##### Reason + + They are readable and don't implicitly convert to pointers. They are not confused with non-standard extensions of built-in arrays. -**Example, bad**: +##### Example, bad const int n = 7; int m = 9; @@ -6746,13 +7527,15 @@ They are not confused with non-standard extensions of built-in arrays. // ... } -**Note**: The definition of `a1` is legal C++ and has always been. +##### Note + +The definition of `a1` is legal C++ and has always been. There is a lot of such code. It is error-prone, though, especially when the bound is non-local. Also, it is a "popular" source of errors (buffer overflow, pointers from array decay, etc.). The definition of `a2` is C but not C++ and is considered a security risk -**Example**: +##### Example const int n = 7; int m = 9; @@ -6764,17 +7547,18 @@ The definition of `a2` is C but not C++ and is considered a security risk // ... } -**Enforcement**: +##### Enforcement * Flag arrays with non-constant bounds (C-style VLAs) * Flag arrays with non-local constant bounds - ### ES.28: Use lambdas for complex initialization, especially of `const` variables -**Reason**: 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. +##### Reason -**Example; bad**: + 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. + +##### Example, bad widget x; // should be const, but: for(auto i=2; i <= N; ++i) { // this could be some @@ -6782,7 +7566,7 @@ The definition of `a2` is C but not C++ and is considered a security risk } // needed to initialize x // from here, x should be const, but we can’t say so in code in this style -**Example; good**: +##### Example, good const widget x = [&]{ widget val; // assume that widget has a default constructor @@ -6792,7 +7576,7 @@ The definition of `a2` is C but not C++ and is considered a security risk return val; }(); -**Example**: +##### Example string var = [&]{ if (!in) return ""; // default @@ -6804,7 +7588,7 @@ The definition of `a2` is C but not C++ and is considered a security risk 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. -**Example**: +##### Example owner in = [&]{ switch (source) { @@ -6813,36 +7597,44 @@ If at all possible, reduce the conditions to a simple set of alternatives (e.g., case file: owned=true; return *new ifstream{argv[2]}; }(); -**Enforcement**: Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it. +##### Enforcement +Hard. At best a heuristic. Look for an uninitialized variable followed by a loop assigning to it. ### ES.30: Don't use macros for program text manipulation -**Reason**: Macros are a major source of bugs. +##### Reason + + Macros are a major source of bugs. Macros don't obey the usual scope and type rules. Macros ensure that the human reader see something different from whet the compiler sees. Macros complicates tool building. -**Example, bad** +##### Example, bad #define Case break; case /* BAD */ This innocuous-looking macro makes a single lower case `c` instead of a `C` into a bad flow-control bug. -**Note**: This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc. +##### Note -**Enforcement**: Scream when you see a macro that isn't just use for source control (e.g., `#ifdef`) +This rule does not ban the use of macros for "configuration control" use in `#ifdef`s, etc. +##### Enforcement + +Scream when you see a macro that isn't just use for source control (e.g., `#ifdef`) ### ES.31: Don't use macros for constants or "functions" -**Reason**: Macros are a major source of bugs. +##### Reason + + Macros are a major source of bugs. Macros don't obey the usual scope and type rules. Macros don't obey the usual rules for argument passing. Macros ensure that the human reader see something different from whet the compiler sees. Macros complicates tool building. -**Example, bad**: +##### Example, bad #define PI 3.14 #define SQUARE(a, b) (a*b) @@ -6852,52 +7644,59 @@ Even if we hadn't left a well-know bug in `SQUARE` there are much better behaved constexpr double pi = 3.14; template T square(T a, T b) { return a*b; } -**Enforcement**: Scream when you see a macro that isn't just use for source control (e.g., `#ifdef`) +##### Enforcement +Scream when you see a macro that isn't just use for source control (e.g., `#ifdef`) ### ES.32: Use `ALL_CAPS` for all macro names -**Reason**: Convention. Readability. Distinguishing macros. +##### Reason -**Example**: + Convention. Readability. Distinguishing macros. + +##### Example #define forever for(;;) /* very BAD */ #define FOREVER for(;;) /* Still evil, but at least visible to humans */ -**Enforcement**: Scream when you see a lower case macro. +##### Enforcement +Scream when you see a lower case macro. ### ES.40: Don't define a (C-style) variadic function -**Reason**: Not type safe. Requires messy cast-and-macro-laden code to get working right. +##### Reason -**Example**: + Not type safe. Requires messy cast-and-macro-laden code to get working right. + +##### Example ??? **Alternative**: Overloading. Templates. Veriadic templates. -**Note**: There are rare used of variadic functions in SFINAE code, but those don't actually run and don't need the `` implementation mess. +##### Note -**Enforcement**: Flag definitions of C-style variadic functions. +There are rare used of variadic functions in SFINAE code, but those don't actually run and don't need the `` implementation mess. +##### Enforcement +Flag definitions of C-style variadic functions. ## ES.stmt: Statements Statements control the flow of control (except for function calls and exception throws, which are expressions). - ### ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice -**Reason**: +##### Reason * Readability. * Efficiency: A `switch` compares against constants and is usually better optimized than a series of tests in an `if`-`then`-`else` chain. * a `switch` is enables some heuristic consistency checking. For example, has all values of an `enum` been covered? If not, is there a `default`? -**Example**: +##### Example void use(int n) { @@ -6917,14 +7716,17 @@ rather than // ... } -**Enforcement**: Flag if-then-else chains that check against constants (only). +##### Enforcement +Flag if-then-else chains that check against constants (only). ### ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice -**Reason**: Readability. Error prevention. Efficiency. +##### Reason -**Example**: + Readability. Error prevention. Efficiency. + +##### Example for(int i=0; i ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable -**Reason**: Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited. +##### Reason -**Example**: + Readability: the complete logic of the loop is visible "up front". The scope of the loop variable can be limited. + +##### Example for (int i = 0; i < vec.size(); i++) { // do work } -**Example, bad**: +##### Example, bad int i = 0; while (i < vec.size()) { @@ -6982,32 +7788,38 @@ This will copy each elements of `vs` into `s`. Better i++; } -**Enforcement**: ??? +##### Enforcement +??? ### ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### ES.74: Prefer to declare a loop variable in the initializer part of as `for`-statement -**Reason**: Limit the loop variable visibility to the scope of the loop. +##### Reason + + Limit the loop variable visibility to the scope of the loop. Avoid using the loop variable for other purposes after the loop. -**Example**: +##### Example for (int i=0; i<100; ++i) { // GOOD: i var is visible only inside the loop // ... } -**Example; don't**: +##### Example, don't int j; // BAD: j is visible outside the loop for (j=0; j<100; ++j) { @@ -7017,18 +7829,21 @@ Avoid using the loop variable for other purposes after the loop. **See also**: [Don't use a variable for two unrelated purposes](#Res-recycle) -**Enforcement**: Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop. +##### Enforcement + +Warn when a variable modified inside the `for`-statement is declared outside the loop and not being used outside the loop. **Discussion**: Scoping the loop variable to the loop body also helps code optimizers greatly. Recognizing that the induction variable is only accessible in the loop body unblocks optimizations such as hoisting, strength reduction, loop-invariant code motion, etc. - ### ES.75: Avoid `do`-statements -**Reason**: Readability, avoidance of errors. +##### Reason + + Readability, avoidance of errors. The termination conditions is at the end (where it can be overlooked) and the condition is not checked the first time through. ??? -**Example**: +##### Example int x; do { @@ -7036,19 +7851,27 @@ The termination conditions is at the end (where it can be overlooked) and the co x } while (x<0); -**Enforcement**: ??? +##### Enforcement + +??? ### ES.76: Avoid `goto` -**Reason**: Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code. +##### Reason -**Exception**: Breaking out of a nested loop. In that case, always jump forwards. + Readability, avoidance of errors. There are better control structures for humans; `goto` is for machine generated code. -**Example**: +##### Exception + +Breaking out of a nested loop. In that case, always jump forwards. + +##### Example ??? -**Example**: There is a fair amount of use of the C goto-exit idiom: +##### Example + +There is a fair amount of use of the C goto-exit idiom: void f() { @@ -7063,32 +7886,37 @@ The termination conditions is at the end (where it can be overlooked) and the co This is an ad-hoc simulation of destructors. Declare your resources with handles with destructors that clean up. -**Enforcement**: +##### Enforcement * 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. - - ### ES.77: ??? `continue` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### ES.78: Always end a `case` with a `break` -**Reason**: ??? loop, switch ??? +##### Reason -**Example**: + ??? loop, switch ??? + +##### Example ??? -**Note**: Multiple case labels of a single statement is OK: +##### Note + +Multiple case labels of a single statement is OK: switch (x) { case 'a': @@ -7098,25 +7926,31 @@ This is an ad-hoc simulation of destructors. Declare your resources with handles break; } -**Enforcement**: ??? +##### Enforcement +??? ### ES.79: ??? `default` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### ES.85: Make empty statements visible -**Reason**: Readability. +##### Reason -**Example**: + Readability. + +##### Example for (i=0; i ES.40: Avoid complicated expressions -**Reason**: Complicated expressions are error-prone. +##### Reason -**Example**: + Complicated expressions are error-prone. + +##### Example while ((c=getc())!=-1) // bad: assignment hidden in subexpression @@ -7156,9 +7993,11 @@ Expressions manipulate values. 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. -**Note**: A programmer should know and use the basic rules for expressions. +##### Note -**Example**: +A programmer should know and use the basic rules for expressions. + +##### Example x=k*y+z; // OK @@ -7171,8 +8010,9 @@ Some of these expressions are unconditionally bad (e.g., they rely on undefined auto t2 = x ES.41: If in doubt about operator precedence, parenthesize -**Reason**: Avoid errors. Readability. Not everyone has the operator table memorized. +##### Reason -**Example**: + Avoid errors. Readability. Not everyone has the operator table memorized. + +##### Example if (a && b==1) // OK? if (a & b==1) // OK? @@ -7198,79 +8039,94 @@ but consider mixing bitwise logical operations with other operators in need of p if (a && b==1) // OK: means a&&(b==1) if (a & b==1) // bad: means (a&b)==1 -**Note**: You should know enough not to need parentheses for +##### Note + +You should know enough not to need parentheses for if (a<0 || a<=max) { // ... } -**Enforcement**: +##### Enforcement * Flag combinations of bitwise-logical operators and other operators. * Flag assignment operators not as the leftmost operator. * ??? - ### ES.42: Keep use of pointers simple and straightforward -**Reason**: Complicated pointer manipulation is a major source of errors. +##### Reason + + Complicated pointer manipulation is a major source of errors. * Do all pointer arithmetic on an `array_view` (exception ++p in simple loop???) * Avoid pointers to pointers * ??? -**Example**: +##### Example ??? -**Enforcement**: We need a heuristic limiting the complexity of pointer arithmetic statement. +##### Enforcement +We need a heuristic limiting the complexity of pointer arithmetic statement. ### ES.43: Avoid expressions with undefined order of evaluation -**Reason**: You have no idea what such code does. Portability. +##### Reason + + You have no idea what such code does. Portability. 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. -**Example**: +##### Example v[i]=++i; // the result is undefined A good rule of thumb is that you should not read a value twice in an expression where you write to it. -**Example**: +##### Example ??? -**Note**: What is safe? +##### Note -**Enforcement**: Can be detected by a good analyzer. +What is safe? +##### Enforcement + +Can be detected by a good analyzer. ### ES.44: Don't depend on order of evaluation of function arguments -**Reason**: that order is unspecified +##### Reason -**Example**: + that order is unspecified + +##### Example int i=0; f(++i,++i); The call will most likely be `f(0, 1)` or `f(1, 0)`, but you don't know which. Technically, the behavior is undefined. -**Example**: ??? overloaded operators can lead to order of evaluation problems (shouldn't :-() +##### Example + +??? overloaded operators can lead to order of evaluation problems (shouldn't :-() f1()->m(f2()); // m(f1(), f2()) cout << f1() << f2(); // operator<<(operator<<(cout, f1()), f2()) +##### Enforcement -**Enforcement**: Can be detected by a good analyzer. - +Can be detected by a good analyzer. ### ES.45: Avoid "magic constants"; use symbolic constants -**Reason**: Unnamed constants embedded in expressions are easily overlooked and often hard to understand: +##### Reason -**Example**: + Unnamed constants embedded in expressions are easily overlooked and often hard to understand: + +##### Example for (int m = 1; m <= 12; ++m) // don't: magic constant 12 cout << month[m] << '\n'; @@ -7287,14 +8143,17 @@ Better still, don't expose constants: for(auto m : month) cout << m << '\n'; -**Enforcement**: Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list. +##### Enforcement +Flag literals in code. Give a pass to `0`, `1`, `nullptr`, `\n`, `""`, and others on a positive list. ### ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions -**Reason**: A narrowing conversion destroys information, often unexpectedly so. +##### Reason -**Example**: + A narrowing conversion destroys information, often unexpectedly so. + +##### Example A key example is basic narrowing: @@ -7309,7 +8168,9 @@ A key example is basic narrowing: char c3 = d; // bad: narrowing } -**Note**: 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: +##### Note + +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: i = narrow_cast(d); // OK (you asked for it): narrowing: i becomes 7 i = narrow(d); // OK: throws narrowing_error @@ -7323,57 +8184,71 @@ We also include lossy arithmetic casts, such as from a negative floating point t u = narrow_cast(d); // OK (you asked for it): u becomes 0 u = narrow(d); // OK: throws narrowing_error +##### Enforcement -**Enforcement**: A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions: +A good analyzer can detect all narrowing conversions. However, flagging all narrowing conversions will lead to a lot of false positives. Suggestions: * flag all floating-point to integer conversions (maybe only float->char and double->int. Here be dragons! we need data) * flag all long->char (I suspect int->char is very common. Here be dragons! we need data) * consider narrowing conversions for function arguments especially suspect - ### ES.47: Use `nullptr` rather than `0` or `NULL` -**Reason**: Readability. Minimize surprises: `nullptr` cannot be confused with an `int`. +##### Reason -**Example**: Consider + Readability. Minimize surprises: `nullptr` cannot be confused with an `int`. + +##### Example + +Consider void f(int); void f(char*); f(0); // call f(int) f(nullptr); // call f(char*) -**Enforcement**: Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation. +##### Enforcement +Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation. ### ES.48: Avoid casts -**Reason**: Casts are a well-known source of errors. Makes some optimizations unreliable. +##### Reason -**Example**: + Casts are a well-known source of errors. Makes some optimizations unreliable. + +##### Example ??? -**Note**: Programmer who write casts typically assumes that they know what they are doing. +##### Note + +Programmer who write casts typically assumes that they know what they are doing. In fact, they often disable the general rules for using values. Overload resolution and template instantiation usually pick the right function if there is a right function to pick. If there is not, maybe there ought to be, rather than applying a local fix (cast). -**Note**: Casts are necessary in a systems programming language. +##### Note + +Casts are necessary in a systems programming language. For example, how else would we get the address of a device register into a pointer. However, casts are seriously overused as well as a major source of errors. -**Note**: If you feel the need for a lot of casts, there may be a fundamental design problem. +##### Note -**Enforcement**: +If you feel the need for a lot of casts, there may be a fundamental design problem. + +##### Enforcement * Force the elimination of C-style casts * Warn against named casts * Warn if there are many functional style casts (there is an obvious problem in quantifying 'many'). - ### ES.49: If you must use a cast, use a named cast -**Reason**: Readability. Error avoidance. +##### Reason + + Readability. Error avoidance. Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors. The named casts are: @@ -7387,51 +8262,66 @@ The named casts are: * `gsl::narrow_cast` // `narrow_cast(x)` is `static_cast(x)` * `gsl::narrow` // `narrow(x)` is `static_cast(x)` if `static_cast(x)==x` or it throws `narrowing_error` -**Example**: +##### Example ??? -**Note**: ??? +##### Note -**Enforcement**: Flag C-style and functional casts. +??? +##### Enforcement + +Flag C-style and functional casts. ## ES.50: Don't cast away `const` -**Reason**: It makes a lie out of `const` +##### Reason -**Note**: Usually the reason to "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object. + It makes a lie out of `const` + +##### Note + +Usually the reason to "cast away `const`" is to allow the updating of some transient information of an otherwise immutable object. Examples are cashing, mnemorization, and precomputation. Such examples are often handled as well or better using `mutable` or an indirection than with a `const_cast`. -**Example**: +##### Example ??? -**Enforcement**: Flag `const_cast`s. +##### Enforcement +Flag `const_cast`s. ### ES.55: Avoid the need for range checking -**Reason**: Constructs that cannot overflow, don't, and usually runs faster: +##### Reason -**Example**: + Constructs that cannot overflow, don't, and usually runs faster: + +##### Example for (auto& x : v) // print all elements of v cout << x << '\n'; auto p = find(v, x); // find x in v -**Enforcement**: Look for explicit range checks and heuristically suggest alternatives. +##### Enforcement +Look for explicit range checks and heuristically suggest alternatives. ### ES.60: Avoid `new` and `delete[]` outside resource management functions -**Reason**: Direct resource management in application code is error-prone and tedious. +##### Reason -**Note**: also known as "No naked `new`!" + Direct resource management in application code is error-prone and tedious. -**Example, bad**: +##### Note + +also known as "No naked `new`!" + +##### Example, bad void f(int n) { @@ -7444,14 +8334,17 @@ There can be code in the `...` part that causes the `delete` never to happen. **See also**: [R: Resource management](#S-resource). -**Enforcement**: Flag naked `new`s and naked `delete`s. +##### Enforcement +Flag naked `new`s and naked `delete`s. ### ES.61: delete arrays using `delete[]` and non-arrays using `delete` -**Reason**: That's what the language requires and mistakes can lead to resource release errors and/or memory corruption. +##### Reason -**Example, bad**: + That's what the language requires and mistakes can lead to resource release errors and/or memory corruption. + +##### Example, bad void f(int n) { @@ -7460,19 +8353,22 @@ There can be code in the `...` part that causes the `delete` never to happen. delete p; // error: just delete the object p, rather than delete the array p[] } -**Note**: This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems. +##### Note -**Enforcement**: +This example not only violates the [no naked `new` rule](#Res-new) as in the previous example, it has many more problems. + +##### Enforcement * if the `new` and the `delete` is in the same scope, mistakes can be flagged. * if the `new` and the `delete` are in a constructor/destructor pair, mistakes can be flagged. - ### ES.62: Don't compare pointers into different arrays -**Reason**: The result of doing so is undefined. +##### Reason -**Example, bad**: + The result of doing so is undefined. + +##### Example, bad void f(int n) { @@ -7482,59 +8378,73 @@ There can be code in the `...` part that causes the `delete` never to happen. if (0 < &a1[5] - &a2[7]) {} // bad: undefined } -**Note**: This example has many more problems. +##### Note -**Enforcement**: +This example has many more problems. +##### Enforcement ## Arithmetic ### ES.100: Don't mix signed and unsigned arithmetic -**Reason**: Avoid wrong results. +##### Reason -**Example**: + Avoid wrong results. + +##### Example ??? -**Note** Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts. +##### Note + +Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts. This precludes consistency. -**Enforcement**: Compilers already know and sometimes warn. +##### Enforcement +Compilers already know and sometimes warn. ### ES.101: use unsigned types for bit manipulation -**Reason**: Unsigned types support bit manipulation without surprises from sign bits. +##### Reason -**Example**: + Unsigned types support bit manipulation without surprises from sign bits. + +##### Example ??? **Exception**: Use unsigned types if you really want modulo arithmetic. -**Enforcement**: ??? +##### Enforcement +??? ### ES.102: Used signed types for arithmetic -**Reason**: Unsigned types support bit manipulation without surprises from sign bits. +##### Reason -**Example**: + Unsigned types support bit manipulation without surprises from sign bits. + +##### Example ??? **Exception**: Use unsigned types if you really want modulo arithmetic. -**Enforcement**: ??? +##### Enforcement +??? ### ES.103: Don't overflow -**Reason**: Overflow usually makes your numeric algorithm meaningless. +##### Reason + + Overflow usually makes your numeric algorithm meaningless. Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior. -**Example, bad**: +##### Example, bad int a[10]; a[10] = 7; // bad @@ -7543,12 +8453,12 @@ Incrementing a value beyond a maximum value can lead to memory corruption and un while (n++<10) a[n-1] = 9; // bad (twice) -**Example, bad**: +##### Example, bad int n = numeric_limits::max(); int m = n+1; // bad -**Example, bad**: +##### Example, bad int area(int h, int w) { return h*w; } @@ -7558,14 +8468,17 @@ Incrementing a value beyond a maximum value can lead to memory corruption and un **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type. -**Enforcement**: ??? +##### Enforcement +??? ### ES.104: Don't underflow -**Reason**: Decrementing a value beyond a maximum value can lead to memory corruption and undefined behavior. +##### Reason -**Example, bad**: + Decrementing a value beyond a maximum value can lead to memory corruption and undefined behavior. + +##### Example, bad int a[10]; a[-2] = 7; // bad @@ -7576,23 +8489,29 @@ Incrementing a value beyond a maximum value can lead to memory corruption and un **Exception**: Use unsigned types if you really want modulo arithmetic. -**Enforcement**: ??? +##### Enforcement +??? ### ES.105: Don't divide by zero -**Reason**: The result is undefined and probably a crash. +##### Reason -**Note**: this also applies to `%`. + The result is undefined and probably a crash. -**Example**: +##### Note + +this also applies to `%`. + +##### Example ??? **Alternative**: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type. -**Enforcement**: ??? +##### Enforcement +??? # PER: Performance @@ -7623,69 +8542,87 @@ Performance rule summary: * [PER.19: Access memory predictably](#Rper-access) * [PER.30: Avoid context switches on the critical path](#Rper-context) - ### PER.1: Don't optimize without reason -**Reason**: If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs. +##### Reason -**Note**: Some people optimize out of habit or because it's fun. + If there is no need for optimization, the main result of the effort will be more errors and higher maintenance costs. + +##### Note + +Some people optimize out of habit or because it's fun. ??? - ### PER.2: Don't optimize prematurely -**Reason**: Elaborately optimized code is usually larger and harder to change than unoptimized code. +##### Reason + + Elaborately optimized code is usually larger and harder to change than unoptimized code. ??? - ### PER.3: Don't optimize something that's not performance critical -**Reason**: Optimizing a non-performance-critical part of a program has no effect on system performance. +##### Reason -**Note**: If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless. + Optimizing a non-performance-critical part of a program has no effect on system performance. + +##### Note + +If your program spends most of its time waiting for the web or for a human, optimization of in-memory computation is probably useless. ??? - - ### PER.4: Don't assume that complicated code is necessarily faster than simple code -**Reason**: Simple code can be very fast. Optimizers sometimes do marvels with simple code +##### Reason -**Note**: ??? + Simple code can be very fast. Optimizers sometimes do marvels with simple code + +##### Note ??? +??? ### PER.5: Don't assume that low-level code is necessarily faster than high-level code -**Reason**: Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code +##### Reason -**Note**: ??? + Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels with high-level code + +##### Note ??? +??? ### PER.6: Don't make claims about performance without measurements -**Reason**: The field of performance is littered with myth and bogus folklore. +##### Reason + + The field of performance is littered with myth and bogus folklore. Modern hardware and optimizers defy naive assumptions; even experts are regularly surprised. -**Note**: Getting good performance measurements can be hard and require specialized tools. +##### Note -**Note**: A few simple microbenchmarks using Unix `time` or the standard library `` can help dispell the most obvious myths. +Getting good performance measurements can be hard and require specialized tools. + +##### Note + +A few simple microbenchmarks using Unix `time` or the standard library `` can help dispell the most obvious myths. If you can't measure your complete system accurately, at least try to measure a few of your key operations and algorithms. A profiler can help tell you which parts of your system are performance critical. Often, you will be surprised. ??? - ### PER.10: Rely on the static type system -**Reason**: Type violations, weak types (e.g. `void*`s), and low level code (e.g., manipulation of sequences as individual bytes) +##### Reason + + 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. ??? @@ -7718,35 +8655,36 @@ make the job of the optimizer much harder. Simple code often optimizes better th ### PER.16: Use compact data structures -**Reason**: Performance is typically dominated by memory access times. +##### Reason + + Performance is typically dominated by memory access times. ??? - ### PER.17: Declare the most used member of a time critical struct first ??? - ### PER.18: Space is time -**Reason**: Performance is typically dominated by memory access times. +##### Reason + + Performance is typically dominated by memory access times. ??? - ### PER.19: Access memory predictably -**Reason**: Performance is very sensitive to cache performance and cache algorithms favor simple (usually linear) access to adjacent data. +##### Reason + + Performance is very sensitive to cache performance and cache algorithms favor simple (usually linear) access to adjacent data. ??? - ### PER.30: Avoid context switches on the critical path ??? - # CP: Concurrency and Parallelism ??? @@ -7763,14 +8701,15 @@ See also: * [CP.simd: SIMD](#SScp-simd) * [CP.free: Lock-free programming](#SScp-free) - ### CP.1: Assume that your code will run as part of a multi-threaded program -**Reason**: It is hard to be certain that concurrency isn't used now or sometime in the future. +##### Reason + + It is hard to be certain that concurrency isn't used now or sometime in the future. Code gets re-used. Libraries using threads my be used from some other part of the program. -**Example**: +##### Example ??? @@ -7781,12 +8720,17 @@ Typically, such programs leads to a painful effort to remove data races. ### CP.2: Avoid data races -**Reason**: Unless you do, nothing is guaranteed to work and subtle errors will persist. +##### Reason -**Note**: If you have any doubts about what this means, go read a book. + Unless you do, nothing is guaranteed to work and subtle errors will persist. -**Enforcement**: Some is possible, do at least something. +##### Note +If you have any doubts about what this means, go read a book. + +##### Enforcement + +Some is possible, do at least something. ## CP.con: Concurrency @@ -7815,7 +8759,6 @@ It should definitely mention that `volatile` does not provide atomicity, does no ???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") - ## CP.par: Parallelism ??? @@ -7825,7 +8768,6 @@ Parallelism rule summary: * ??? * ??? - ## CP.simd: SIMD ??? @@ -7846,7 +8788,9 @@ Lock-free programming rule summary: ### Don't use lock-free programming unless you absolutely have to -**Reason**: It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures. +##### Reason + + It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures. **Alternative**: Use lock-free data structures implemented by others as part of some library. @@ -7893,16 +8837,19 @@ Error-handling rule summary: * [E.25: ??? What to do in programs where exceptions cannot be thrown](#Re-no-throw) * ??? - ### E.1: Develop an error-handling strategy early in a design -**Reason**: a consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system. +##### Reason + + a consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system. ### E.2: Throw an exception to signal that a function can't perform its assigned task -**Reason**: To make error handling systematic, robust, and non-repetitive. +##### Reason -**Example**: + To make error handling systematic, robust, and non-repetitive. + +##### Example struct Foo { vector v; @@ -7932,7 +8879,9 @@ The `File_handle` constructor might defined like this throw runtime_error{"File_handle: could not open "S-+ name + " as " + mode"} } -**Note**: It is often said that exceptions are meant to signal exceptional events and failures. +##### Note + +It is often said that exceptions are meant to signal exceptional events and failures. However, that's a bit circular because "what is exceptional?" Examples: @@ -7944,7 +8893,9 @@ Examples: In contrast, termination of an ordinary loop is not exceptional. Unless the loop was meant to be infinite, termination is normal and expected. -**Note**: Don't use a `throw` as simply an alternative way of returning a value from a function. +##### Note + +Don't use a `throw` as simply an alternative way of returning a value from a function. **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`. @@ -7952,13 +8903,14 @@ Unless the loop was meant to be infinite, termination is normal and expected. **See also**: [discussion](#Sd-noexcept) - ### E.3: Use exceptions for error handling only -**Reason**. To keep error handling separated from "ordinary code." +##### Reason + +To keep error handling separated from "ordinary code." C++ implementations tend to be optimized based on the assumption that exceptions are rare. -**Example; don't**: +##### Example, don't int find_index(vector& vec, const string& x) // don't: exception not used for error handling { @@ -7974,34 +8926,41 @@ C++ implementations tend to be optimized based on the assumption that exceptions This is more complicated and most likely runs much slower than the obvious alternative. There is nothing exceptional about finding a value in a `vector`. - ### E.4: Design your error-handling strategy around invariants -**Reason**: To use an objects it must be in a valid state (defined formally or informally by an invariant) +##### Reason + + 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. -**Note**: 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. +##### Note +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. ### E.5: Let a constructor establish an invariant, and throw if it cannot -**Reason**: Leaving an object without its invariant established is asking for trouble. +##### Reason + + Leaving an object without its invariant established is asking for trouble. Not all member function can be called. -**Example**: +##### Example ??? **See also**: [If a constructor cannot construct a valid object, throw an exception](#Rc-throw) -**Enforcement**: ??? +##### Enforcement +??? ### E.6: Use RAII to prevent leaks -**Reason**: Leaks are typically unacceptable. RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks. +##### Reason -**Example**: + Leaks are typically unacceptable. RAII ("Resource Acquisition Is Initialization") is the simplest, most systematic way of preventing leaks. + +##### Example void f1(int i) // Bad: possibly leak { @@ -8054,9 +9013,13 @@ Unless you really need pointer semantics, use a local resource object: // ... } -**Note**: If there is no obvious resource handle, cleanup actions can be represented by a [`final_action` object](#Re-finally) +##### Note -**Note**: But what do we do if we are writing a program where exceptions cannot be used? +If there is no obvious resource handle, cleanup actions can be represented by a [`final_action` object](#Re-finally) + +##### Note + +But what do we do if we are writing a program where exceptions cannot be used? First challenge that assumption; there are many anti-exceptions myths around. We know of only a few good reasons: @@ -8094,28 +9057,33 @@ Prefer to use exceptions. **See also**: [discussion](#Sd-noexcept). -**Enforcement**: ??? +##### Enforcement +??? ### E.7: State your preconditions -**Reason**: To avoid interface errors. +##### Reason + + To avoid interface errors. **See also**: [precondition rule](#Ri-pre). - ### E.8: State your postconditions -**Reason**: To avoid interface errors. +##### Reason + + To avoid interface errors. **See also**: [postcondition rule](#Ri-post). - ### E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable -**Reason**: To make error handling systematic, robust, and efficient. +##### Reason -**Example**: + To make error handling systematic, robust, and efficient. + +##### Example double compute(double d) noexcept { @@ -8124,9 +9092,11 @@ Prefer to use exceptions. 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`. -**Note**: Many standard library functions are `noexcept` including all the standard library functions "inherited" from the C standard library. +##### Note -**Example**: +Many standard library functions are `noexcept` including all the standard library functions "inherited" from the C standard library. + +##### Example vector munge(const vector& v) noexcept { @@ -8138,12 +9108,13 @@ The `noexcept` here states that I am not willing or able to handle the situation **See also**: [discussion](#Sd-noexcept). - ### E.13: Never throw while being the direct owner of an object -**Reason**: That would be a leak. +##### Reason -**Example**: + That would be a leak. + +##### Example void leak(int x) // don't: may leak { @@ -8165,12 +9136,13 @@ One way of avoiding such problems is to use resource handles consistently: **See also**: ???resource rule ??? - ### E.14: Use purpose-designed user-defined types as exceptions (not built-in types) -**Reason**: A user-defined type is unlikely to clash with other people's exceptions. +##### Reason -**Example**: + A user-defined type is unlikely to clash with other people's exceptions. + +##### Example void my_code() { @@ -8191,7 +9163,7 @@ One way of avoiding such problems is to use resource handles consistently: } } -**Example; don't**: +##### Example, don't void my_code() // Don't { @@ -8212,9 +9184,11 @@ One way of avoiding such problems is to use resource handles consistently: } } -**Note**: 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. +##### Note -**Example; don't**: +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. + +##### Example, don't void my_code() // Don't { @@ -8235,17 +9209,19 @@ One way of avoiding such problems is to use resource handles consistently: } } - **See also**: [Discussion](#Sd-???) -**Enforcement**: 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. +##### Enforcement +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. ### E.15: Catch exceptions from a hierarchy by reference -**Reason**: To prevent slicing. +##### Reason -**Example**: + To prevent slicing. + +##### Example void f() try { @@ -8259,14 +9235,17 @@ Instead, use catch (exception& e) { /* ... */ } -**Enforcement**: Flag by-value exceptions if their type are part of a hierarchy (could require whole-program analysis to be perfect). +##### Enforcement +Flag by-value exceptions if their type are part of a hierarchy (could require whole-program analysis to be perfect). ### E.16: Destructors, deallocation, and `swap` must never fail -**Reason**: 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. +##### Reason -**Example; don't**: + 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. + +##### Example, don't class Connection { // ... @@ -8278,24 +9257,33 @@ Instead, use } }; -**Note**: 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. +##### Note -**Note**: 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. +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. -**Note**: Deallocation functions, including `operator delete`, must be `noexcept`. `swap` functions must be `noexcept`. Most destructors are implicitly `noexcept` by default. destructors, make them `noexcept`. +##### Note -**Enforcement**: Catch destructors, deallocation operations, and `swap`s that `throw`. Catch such operations that are not `noexcept`. +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. + +##### Note + +Deallocation functions, including `operator delete`, must be `noexcept`. `swap` functions must be `noexcept`. Most destructors are implicitly `noexcept` by default. destructors, make them `noexcept`. + +##### Enforcement + +Catch destructors, deallocation operations, and `swap`s that `throw`. Catch such operations that are not `noexcept`. **See also**: [discussion](#Sd-never-fail) - ### E.17: Don't try to catch every exception in every function -**Reason**: Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste. +##### Reason + + Catching an exception in a function that cannot take a meaningful recovery action leads to complexity and waste. Let an exception propagate until it reaches a function that can handle it. Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii). -**Example; don't**: +##### Example, don't void f() // bad { @@ -8307,28 +9295,32 @@ Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii). } } -**Enforcement**: +##### Enforcement * Flag nested try-blocks. * Flag source code files with a too high ratio of try-blocks to functions. (??? Problem: define "too high") - ### E.18: Minimize the use of explicit `try`/`catch` -**Reason**: `try`/`catch` is verbose and non-trivial uses error-prone. +##### Reason -**Example**: + `try`/`catch` is verbose and non-trivial uses error-prone. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available -**Reason**: `finally` is less verbose and harder to get wrong than `try`/`catch`. +##### Reason -**Example**: + `finally` is less verbose and harder to get wrong than `try`/`catch`. + +##### Example void f(int n) { @@ -8339,15 +9331,14 @@ Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii). **See also** ???? - ### E.25: ??? What to do in programs where exceptions cannot be thrown -**Note**: ??? mostly, you can afford exceptions and code gets simpler with exceptions ??? +##### Note +??? mostly, you can afford exceptions and code gets simpler with exceptions ??? **See also**: [Discussion](#Sd-???). - # Con: Constants and Immutability You can't have a race condition on a constant. @@ -8362,63 +9353,77 @@ Constant rule summary: * [Con.4: Use `const` to define objects with values that do not change after construction](#Rconst-const) * [Con.5: Use `constexpr` for values that can be computed at compile time](#Rconst-constexpr) - ### Con.1: By default, make objects immutable -**Reason**: Immutable objects are easier to reason about, so make object non-`const` only when there is a need to change their value. +##### Reason -**Example**: + Immutable objects are easier to reason about, so make object non-`const` only when there is a need to change their value. + +##### Example for ( container ??? -**Enforcement**: ??? +##### Enforcement +??? ### Con.2: By default, make member functions `const` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Con.3: By default, pass pointers and references to `const`s -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Con.4: Use `const` to define objects with values that do not change after construction -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### Con.5: Use `constexpr` for values that can be computed at compile time -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? # T: Templates and generic programming @@ -8526,9 +9531,13 @@ Generic programming is programming using types and algorithms parameterized by t ### T.1: Use templates to raise the level of abstraction of code -**Reason**: Generality. Re-use. Efficiency. Encourages consistent definition of user types. +##### Reason -**Example, bad**: 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": + Generality. Re-use. Efficiency. Encourages consistent definition of user types. + +##### Example, bad + + 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": template // requires Incrementable @@ -8549,7 +9558,7 @@ Generic programming is programming using types and algorithms parameterized by t Assuming that `Incrementable` does not support `+` and `Simple_number` does not support `+=`, we have overconstrained implementers of `sum1` and `sum2`. And, in this case, missed an opportunity for a generalization. -**Example**: +##### Example template // requires Arithmetic @@ -8565,25 +9574,32 @@ can be user for a wide variety of algorithms. For additional generality and reusability, we could also use a more general `Container` or `Range` concept instead of committing to only one container, `vector`. -**Note**: If we define a template to require exactly the operations required for a single implementation of a single algorithm +##### Note + +If we define a template to require exactly the operations required for a single implementation of a single algorithm (e.g., requiring just `+=` rather than also `=` and `+`) and only those, we have overconstrained maintainers. We aim to minimize requirements on template arguments, but the absolutely minimal requirements of an implementation is rarely a meaningful concept. -**Note**: Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates) +##### Note + +Templates can be used to express essentially everything (they are Turing complete), but the aim of generic programming (as expressed using templates) is to efficiently generalize operations/algorithms over a set of types with similar semantic properties. -**Enforcement**: +##### Enforcement * Flag algorithms with "overly simple" requirements, such as direct use of specific operators without a concept. * Do not flag the definition of the "overly simple" concepts themselves; they may simply be building blocks for more useful concepts. - ### T.2: Use templates to express algorithms that apply to many argument types -**Reason**: Generality. Minimizing the amount of source code. Interoperability. Re-use. +##### Reason -**Example**: That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range: + Generality. Minimizing the amount of source code. Interoperability. Re-use. + +##### Example + +That's the foundation of the STL. A single `find` algorithm easily works with any kind of input range: template // requires Input_iterator @@ -8593,18 +9609,23 @@ is to efficiently generalize operations/algorithms over a set of types with simi // ... } -**Note**: Don't use a template unless you have a realistic need for more than one template argument type. +##### Note + +Don't use a template unless you have a realistic need for more than one template argument type. Don't overabstract. -**Enforcement**: ??? tough, probably needs a human +##### Enforcement +??? tough, probably needs a human ### T.3: Use templates to express containers and ranges -**Reason**: Containers need an element type, and expressing that as a template argument is general, reusable, and type safe. +##### Reason + + Containers need an element type, and expressing that as a template argument is general, reusable, and type safe. It also avoids brittle or inefficient workarounds. Convention: That's the way the STL does it. -**Example**: +##### Example template // requires Regular @@ -8617,7 +9638,7 @@ It also avoids brittle or inefficient workarounds. Convention: That's the way th vector v(10); v[7] = 9.9; -**Example, bad**: +##### Example, bad class Container { // ... @@ -8636,28 +9657,31 @@ Hiding the `void*` behind macros simply obscures the problems and introduces new you might have to provide a base implementation and express the (type-safe) template in terms of that. See [Stable base](#Rt-abi). -**Enforcement**: +##### Enforcement * Flag uses of `void*`s and casts outside low-level implementation code - ### T.4: Use templates to express syntax tree manipulation -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? **Exceptions**: ??? - - ### T.5: Combine generic and OO techniques to amplify their strengths, not their costs -**Reason**: Generic and OO techniques are complementary. +##### Reason -**Example**: Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces. + Generic and OO techniques are complementary. + +##### Example + +Static helps dynamic: Use static polymorphism to implement dynamically polymorphic interfaces. class Command { // pure virtual functions @@ -8669,11 +9693,15 @@ See [Stable base](#Rt-abi). // implement virtuals }; -**Example**: 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).) +##### Example -**Note**: 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. +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).) -**Enforcement**: +##### Note + +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. + +##### Enforcement * Flag a class template that declares new (non-inherited) virtual functions. @@ -8703,17 +9731,18 @@ Concept definition rule summary: * [T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax](#Rt-use) * ??? - ## T.con-use: Concept use ### T.10: Specify concepts for all template arguments -**Reason**: Correctness and readability. +##### Reason + + Correctness and readability. The assumed meaning (syntax and semantics) of a template argument is fundamental to the interface of a template. A concept dramatically improves documentation and error handling for the template. Specifying concepts for template arguments is a powerful design tool. -**Example**: +##### Example template requires Input_iterator @@ -8732,7 +9761,9 @@ or equivalently and more succinctly // ... } -**Note**: Until your compilers support the concepts language feature, leave the concepts in comments: +##### Note + +Until your compilers support the concepts language feature, leave the concepts in comments: template // requires Input_iterator @@ -8742,23 +9773,30 @@ or equivalently and more succinctly // ... } -**Note**: Plain `typename` (or `auto`) is the least constraining concept. +##### Note + +Plain `typename` (or `auto`) is the least constraining concept. It should be used only rarely when nothing more than "it's a type" can be assumed. This is typically only needed when (as part of template metaprogramming code) we manipulate pure expression trees, postponing type checking. **References**: TC++PL4, Palo Alto TR, Sutton -**Enforcement**: Flag template type arguments without concepts +##### Enforcement +Flag template type arguments without concepts ### T.11: Whenever possible use standard concepts -**Reason**: "Standard" concepts (as provided by the GSL, the ISO concepts TS, and hopefully soon the ISO standard itself) +##### Reason + + "Standard" concepts (as provided by the GSL, the ISO concepts TS, and hopefully soon the ISO standard itself) 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. -**Note**: Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library. +##### Note -**Example**: +Unless you are creating a new generic library, most of the concepts you need will already be defined by the standard library. + +##### Example concept Ordered_container = Sequence && Random_access> && Ordered>; // don't define this: Sortable is in the GSL @@ -8771,36 +9809,46 @@ It is better and simpler just to use `Sortable`: void sort(Sortable& s); // better -**Note**: The set of "standard" concepts is evolving as we approaches real (ISO) standardization. +##### Note -**Note**: Designing a useful concept is challenging. +The set of "standard" concepts is evolving as we approaches real (ISO) standardization. -**Enforcement**: Hard. +##### Note + +Designing a useful concept is challenging. + +##### Enforcement + +Hard. * Look for unconstrained arguments, templates that use "unusual"/non-standard concepts, templates that use "homebrew" concepts without axioms. * Develop a concept-discovery tool (e.g., see [an early experiment](http://www.stroustrup.com/sle2010_webversion.pdf). - ### T.12: Prefer concept names over `auto` for local variables -**Reason**: `auto` is the weakest concept. Concept names convey more meaning than just `auto`. +##### Reason -**Example**: + `auto` is the weakest concept. Concept names convey more meaning than just `auto`. + +##### Example vector v; auto& x = v.front(); // bad String& s = v.begin(); // good -**Enforcement**: +##### Enforcement * ??? - ### T.13: Prefer the shorthand notation for simple, single-type argument concepts -**Reason**: Readability. Direct expression of an idea. +##### Reason -**Example**: To say "`T` is `Sortable`": + Readability. Direct expression of an idea. + +##### Example + +To say "`T` is `Sortable`": template // Correct but verbose: "The parameter is requires Sortable // of type T which is the name of a type @@ -8813,24 +9861,24 @@ It is better and simpler just to use `Sortable`: The shorter versions better match the way we speak. Note that many templates don't need to use the `template` keyword. -**Enforcement**: +##### Enforcement * Not feasible in the short term when people convert from the `` and ` notation. * Later, flag declarations that first introduces a typename and then constrains it with a simple, single-type-argument concept. - ## T.con-def: Concept definition rules ??? - ### T.20: Avoid "concepts" without meaningful semantics -**Reason**: Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered." +##### Reason + + Concepts are meant to express semantic notions, such as "a number", "a range" of elements, and "totally ordered." Simple constraints, such as "has a `+` operator" and "has a `>` operator" cannot be meaningfully specified in isolation and should be used only as building blocks for meaningful concepts, rather than in user code. -**Example, bad**: +##### Example, bad template concept Addable = has_plus; // bad; insufficient @@ -8852,9 +9900,11 @@ and should be used only as building blocks for meaningful concepts, rather than Maybe the concatenation was expected. More likely, it was an accident. Defining minus equivalently would give dramatically different sets of accepted types. This `Addable` violates the mathematical rule that addition is supposed to be commutative: `a+b == b+a`, -**Note**: The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint. +##### Note -**Example (using TS concepts)**: +The ability to specify a meaningful semantics is a defining characteristic of a true concept, as opposed to a syntactic constraint. + +##### Example (using TS concepts) template // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules @@ -8877,19 +9927,22 @@ This `Addable` violates the mathematical rule that addition is supposed to be co string yy = "9"; auto zz = plus(xx, yy); // error: string is not a Number -**Note**: Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept. +##### Note -**Enforcement**: +Concepts with multiple operations have far lower chance of accidentally matching a type than a single-operation concept. + +##### Enforcement * Flag single-operation `concepts` when used outside the definition of other `concepts`. * Flag uses of `enable_if` that appears to simulate single-operation `concepts`. - ### T.21: Define concepts to define complete sets of operations -**Reason**: Improves interoperability. Helps implementers and maintainers. +##### Reason -**Example, bad**: + Improves interoperability. Helps implementers and maintainers. + +##### Example, bad template Subtractable = requires(T a, T, b) { a-b; } // correct syntax? @@ -8900,16 +9953,19 @@ Examples of complete sets are * `Arithmetic`: `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=` * `Comparable`: `<`, `>`, `<=`, `>=`, `==`, `!=` -**Enforcement**: ??? +##### Enforcement +??? ### T.22: Specify axioms for concepts -**Reason**: A meaningful/useful concept has a semantic meaning. +##### Reason + + A meaningful/useful concept has a semantic meaning. 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. Specifying semantics is a powerful design tool. -**Example**: +##### Example template // The operators +, -, *, and / for a number are assumed to follow the usual mathematical rules @@ -8921,18 +9977,26 @@ Specifying semantics is a powerful design tool. {a/b} -> T; }; -**Note** This is an axiom in the mathematical sense: something that may be assumed without proof. +##### Note + +This is an axiom in the mathematical sense: something that may be assumed without proof. In general, axioms are not provable, and when they are the proof is often beyond the capability of a compiler. An axiom may not be general, but the template writer may assume that it holds for all inputs actually used (similar to a precondition). -**Note**: In this context axioms are Boolean expressions. +##### Note + +In this context axioms are Boolean expressions. See the [Palo Alto TR](#S-references) for examples. Currently, C++ does not support axioms (even the ISO Concepts TS), so we have to make do with comments for a longish while. Once language support is available, the `//` in front of the axiom can be removed -**Note**: The GSL concepts have well defined semantics; see the Palo Alto TR and the Ranges TS. +##### Note -**Exception**: Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics. +The GSL concepts have well defined semantics; see the Palo Alto TR and the Ranges TS. + +##### Exception + +Early versions of a new "concept" still under development will often just define simple sets of constraints without a well-specified semantics. Finding good semantics can take effort and time. An incomplete set of constraints can still be very useful: @@ -8941,16 +10005,17 @@ An incomplete set of constraints can still be very useful: A "concept" that is incomplete or without a well-specified semantics can still be useful. However, it should not be assumed to be stable. Each new use case may require such an incomplete concepts to be improved. -**Enforcement**: +##### Enforcement * Look for the word "axiom" in concept definition comments - ### T.23: Differentiate a refined concept from its more general case by adding new use patterns. -**Reason**: Otherwise they cannot be distinguished automatically by the compiler. +##### Reason -**Example**: + Otherwise they cannot be distinguished automatically by the compiler. + +##### Example template concept bool Input_iterator = requires (I iter) { ++iter; }; @@ -8964,16 +10029,17 @@ If two concepts have exactly the same requirements, they are logically equivalen This also decreases the burden on implementers of these types since they do not need any special declarations to "hook into the concept". -**Enforcement**: +##### Enforcement * 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). - ### T.24: Use tag classes or traits to differentiate concepts that differ only in semantics. -**Reason**: Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them. +##### Reason -**Example**: + Two concepts requiring the same syntax but having different semantics leads to ambiguity unless the programmer differentiates them. + +##### Example template // iterator providing random access concept bool RA_iter = ...; @@ -8984,22 +10050,27 @@ they do not need any special declarations to "hook into the concept". The programmer (in a library) must define `is_contiguous` (a trait) appropriately. -**Note**: Traits can be trains classes or type traits. +##### Note + +Traits can be trains classes or type traits. These can be user-defined or standard-library ones. Prefer the standard-library ones. -**Enforcement**: +##### Enforcement * The compiler flags ambiguous use of identical concepts. * Flag the definition of identical concepts. - ### T.25: Avoid negating constraints. -**Reason**: Clarity. Maintainability. +##### Reason + + Clarity. Maintainability. Functions with complementary requirements expressed using negation are brittle. -**Example**: Initially, people will try to define functions with complementary requirements: +##### Example + +Initially, people will try to define functions with complementary requirements: template requires !C // bad @@ -9027,22 +10098,25 @@ version of `f()`, then delete it. The compiler will select the overload and emit an appropriate error. -**Enforcement**: +##### Enforcement + * Flag pairs of functions with `C` and `!C` constraints * Flag all constraint negation - ### T.27: Prefer to define concepts in terms of use-patterns rather than simple syntax -**Reason**: The definition is more readable and corresponds directly to what a user has to write. +##### Reason + + The definition is more readable and corresponds directly to what a user has to write. Conversions are taken into account. You don't have to remember the names of all the type traits. -**Example**: +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ## Template interfaces @@ -9050,10 +10124,12 @@ Conversions are taken into account. You don't have to remember the names of all ### T.40: Use function objects to pass operations to algorithms -**Reason**: Function objects can carry more information through an interface than a "plain" pointer to function. +##### Reason + + Function objects can carry more information through an interface than a "plain" pointer to function. In general, passing function objects give better performance than passing pointers to functions. -**Example**: +##### Example bool greater(double x, double y) { return x>y; } sort(v, greater); // pointer to function: potentially slow @@ -9067,38 +10143,48 @@ In general, passing function objects give better performance than passing pointe ??? these lambdas are crying out for auto parameters -- any objection to making the change? -**Note**: Lambdas generate function objects. +##### Note -**Note**: The performance argument depends on compiler and optimizer technology. +Lambdas generate function objects. -**Enforcement**: +##### Note + +The performance argument depends on compiler and optimizer technology. + +##### Enforcement * Flag pointer to function template arguments. * Flag pointers to functions passed as arguments to a template (risk of false positives). - ### T.41: Require complete sets of operations for a concept -**Reason**: Ease of comprehension. +##### Reason + + Ease of comprehension. Improved interoperability. Flexibility for template implementers. -**Note**: The issue here is whether to require the minimal set of operations for a template argument +##### Note + +The issue here is whether to require the minimal set of operations for a template argument (e.g., `==` but not `!=` or `+` but not `+=`). The rule supports the view that a concept should reflect a (mathematically) coherent set of operations. -**Example**: +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.42: Use template aliases to simplify notation and hide implementation details -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example template class matrix { @@ -9109,26 +10195,27 @@ The rule supports the view that a concept should reflect a (mathematically) cohe 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::`. -**Example**: +##### Example template using Value_type = container_traits::value_type; This saves the user of `Value_type` from having to know the technique used to implement `value_type`s. -**Enforcement**: +##### Enforcement * Flag use of `typename` as a disambiguator outside `using` declarations. * ??? - ### T.43: Prefer `using` over `typedef` for defining aliases -**Reason**: Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration. +##### Reason + + Improved readability: With `using`, the new name comes first rather than being embedded somewhere in a declaration. Generality: `using` can be used for template aliases, whereas `typedef`s can't easily be templates. Uniformity: `using` is syntactically similar to `auto`. -**Example**: +##### Example typedef int (*PFI)(int); // OK, but convoluted @@ -9140,117 +10227,145 @@ Uniformity: `using` is syntactically similar to `auto`. template using PFT2 = int (*)(T); // OK -**Enforcement**: +##### Enforcement * Flag uses of `typedef`. This will give a lot of "hits" :-( - ### T.44: Use function templates to deduce class template argument types (where feasible) -**Reason**: Writing the template argument types explicitly can be tedious and unnecessarily verbose. +##### Reason -**Example**: + Writing the template argument types explicitly can be tedious and unnecessarily verbose. + +##### Example tuple t1 = {1, "Hamlet", 3.14}; // explicit type auto t2 = make_tuple(1, "Ophelia"s, 3.14); // better; deduced type Note the use of the `s` suffix to ensure that the string is a `std::string`, rather than a C-style string. -**Note**: Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions may become redundant in the future. +##### Note -**Exception**: Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly: +Since you can trivially write a `make_T` function, so could the compiler. Thus, `make_T` functions may become redundant in the future. + +##### Exception + +Sometimes there isn't a good way of getting the template arguments deduced and sometimes, you want to specify the arguments explicitly: vector v = { 1, 2, 3, 7.9, 15.99 }; list lst; -**Enforcement**: Flag uses where an explicitly specialized type exactly matches the types of the arguments used. - +##### Enforcement +Flag uses where an explicitly specialized type exactly matches the types of the arguments used. ### T.46: Require template arguments to be at least `Regular` or `SemiRegular` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.47: Avoid highly visible unconstrained templates with common names -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement + +??? ### T.48: If your compiler does not support concepts, fake them with `enable_if` -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.49: Where possible, avoid type-erasure -**Reason**: Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary. +##### Reason -**Example**: + Type erasure incurs an extra level of indirection by hiding type information behind a separate compilation boundary. + +##### Example ??? **Exceptions**: Type erasure is sometimes appropriate, such as for `std::function`. -**Enforcement**: ??? +##### Enforcement +??? ### T.50: Avoid writing an unconstrained template in the same namespace as a type -**Reason**: ADL will find the template even when you think it shouldn't. +##### Reason -**Example**: + ADL will find the template even when you think it shouldn't. + +##### Example ??? -**Note**: 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. +##### Note -**Enforcement**: ??? 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` +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. +##### Enforcement +??? 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` ## TCP.def: Template definitions ??? - ### T.60: Minimize a template's context dependencies -**Reason**: Eases understanding. Minimizes errors from unexpected dependencies. Eases tool creation. +##### Reason -**Example**: + Eases understanding. Minimizes errors from unexpected dependencies. Eases tool creation. + +##### Example ??? -**Note**: Having a template operate only on its arguments would be one way of reducing the number of dependencies to a minimum, +##### Note + +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. -**Enforcement**: ??? Tricky +##### Enforcement +??? Tricky ### T.61: Do not over-parameterize members (SCARY) -**Reason**: A member that does not depend on a template parameter cannot be used except for a specific template argument. +##### Reason + + A member that does not depend on a template parameter cannot be used except for a specific template argument. This limits use and typically increases code size. -**Example, bad**: +##### Example, bad template // requires Regular && Allocator @@ -9271,7 +10386,6 @@ This limits use and typically increases code size. Node* head; }; - List lst1; List lst2; @@ -9305,17 +10419,18 @@ This looks innocent enough, but ??? ??? -**Enforcement**: +##### Enforcement * Flag member types that do not depend on every template argument * Flag member functions that do not depend on every template argument - ### T.62: Place non-dependent template members in a non-templated base class -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example template class Foo { @@ -9337,60 +10452,76 @@ This looks innocent enough, but ??? // ... }; -**Note**: A more general version of this rule would be +##### Note + +A more general version of this rule would be "If a template class member depends on only N template parameters out of M, place it in a base class with only N parameters." For N==1, we have a choice of a base class of a class in the surrounding scope as in [T.41](#Rt-scary). ??? What about constants? class statics? -**Enforcement**: +##### Enforcement * Flag ??? - ### T.64: Use specialization to provide alternative implementations of class templates -**Reason**: A template defines a general interface. +##### Reason + + A template defines a general interface. Specialization offers a powerful mechanism for providing alternative implementations of that interface. -**Example**: +##### Example ??? string specialization (==) ??? representation specialization ? -**Note**: ??? +##### Note -**Enforcement**: ??? +??? +##### Enforcement + +??? ### T.65: Use tag dispatch to provide alternative implementations of a function -**Reason**: A template defines a general interface. ??? +##### Reason -**Example**: + A template defines a general interface. ??? + +##### Example ??? that's how we get algorithms like `std::copy` which compiles into a `memmove` call if appropriate for the arguments. -**Note**: When `concept`s become available such alternatives can be distinguished directly. +##### Note -**Enforcement**: ??? +When `concept`s become available such alternatives can be distinguished directly. +##### Enforcement + +??? ### T.66: Use selection using `enable_if` to optionally define a function -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point -**Reason**: To provide only intended flexibility, and avoid accidental environmental changes. +##### Reason + + To provide only intended flexibility, and avoid accidental environmental changes. 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). @@ -9418,7 +10549,7 @@ There are three major ways to let calling code customize a template. test_traits::value_type x; } -**Enforcement**: +##### Enforcement * 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. @@ -9428,12 +10559,13 @@ Templates are the backbone of C++'s support for generic programming and class hi for object-oriented programming. The two language mechanisms can be use effectively in combination, but a few design pitfalls must be avoided. - ### T.80: Do not naively templatize a class hierarchy -**Reason**: Templatizing a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat. +##### Reason -**Example, bad**: + Templatizing a class hierarchy that has many functions, especially many virtual functions, can lead to code bloat. + +##### Example, bad template struct Container { // an interface @@ -9460,18 +10592,23 @@ Similar for `vector::sort()`. Unless those two functions are called that's code bloat. Imagine what this would do to a class hierarchy with dozens of member functions and dozens of derived classes with many instantiations. -**Note**: In many cases you can provide a stable interface by not parameterizing a base; see [Rule](#Rt-abi). +##### Note -**Enforcement**: +In many cases you can provide a stable interface by not parameterizing a base; see [Rule](#Rt-abi). + +##### Enforcement * Flag virtual functions that depend on a template argument. ??? False positives - ### T.81: Do not mix hierarchies and arrays -**Reason**: An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results. +##### Reason -**Example**: Assume that `Apple` and `Pear` are two kinds of `Fruit`s. + An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results. + +##### Example + +Assume that `Apple` and `Pear` are two kinds of `Fruit`s. void maul(Fruit* p) { @@ -9508,29 +10645,33 @@ Note that `maul()` violates the a `T*` points to an individual object [Rule](#?? Note that the assignment in `maul2()` violated the no-slicing [Rule](#???). -**Enforcement**: +##### Enforcement * Detect this horror! - ### T.82: Linearize a hierarchy when virtual functions are undesirable -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.83: Do not declare a member function template virtual -**Reason** C++ does not support that. +##### Reason + +C++ does not support that. If it did, vtbls could not be generated until link time. And in general, implementations must deal with dynamic linking. -**Example; don't**: +##### Example, don't class Shape { // ... @@ -9540,15 +10681,19 @@ And in general, implementations must deal with dynamic linking. **Alternative**: ??? double dispatch, visitor, calculate which function to call -**Enforcement**: The compiler handles that. - +##### Enforcement +The compiler handles that. ### T.84: Use a non-template core implementation to provide an ABI-stable interface -**Reason**: Improve stability of code. Avoids code bloat. +##### Reason -**Example**: It could be a base class: + Improve stability of code. Avoids code bloat. + +##### Example + +It could be a base class: struct Link_base { // stable Link* suc; @@ -9585,59 +10730,69 @@ Instead of using a separate "base" type, another common technique is to speciali **Alternative**: Use a [PIMPL](#???) implementation. -**Enforcement**: ??? +##### Enforcement +??? ## T.var: Variadic template rules ??? - ### T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types -**Reason**: Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs. +##### Reason -**Example**: + Variadic templates is the most general mechanism for that, and is both efficient and type-safe. Don't use C varargs. + +##### Example ??? printf -**Enforcement**: +##### Enforcement * Flag uses of `va_arg` in user code. - ### T.101: ??? How to pass arguments to a variadic template ??? -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? beware of move-only and reference arguments -**Enforcement**: ??? +##### Enforcement +??? ### T.102: How to process arguments to a variadic template -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? forwarding, type checking, references -**Enforcement**: ??? +##### Enforcement +??? ### T.103: Don't use variadic templates for homogeneous argument lists -**Reason** There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`. +##### Reason -**Example**: +There are more precise ways of specifying a homogeneous sequence, such as an `initializer_list`. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ## T.meta: Template metaprogramming (TMP) @@ -9647,39 +10802,43 @@ Metaprogramming is programming where at least one input or one result is a type. Templates offer Turing-complete (modulo memory capacity) duck typing at compile time. The syntax and techniques needed are pretty horrendous. - ### T.120: Use template metaprogramming only when you really need to -**Reason**: Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain. +##### Reason + + Template metaprogramming is hard to get right, slows down compilation, and is often very hard to maintain. However, there are real-world examples where template metaprogramming provides better performance that any alternative short of expert-level assembly code. Also, there are real-world examples where template metaprogramming expresses the fundamental ideas better than run-time code. 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++. -**Example, bad**: +##### Example, bad ??? -**Example, bad**: +##### Example, bad enable_if Instead, use concepts. But see [How to emulate concepts if you don't have language support](#Rt-emulate). -**Example**: +##### Example ??? good **Alternative**: If the result is a value, rather than a type, use a [`constexpr` function](#Rt-fct). -**Note**: If you feel the need to hide your template metaprogramming in macros, you have probably gone too far. +##### Note +If you feel the need to hide your template metaprogramming in macros, you have probably gone too far. ### T.121: Use template metaprogramming primarily to emulate concepts -**Reason**: Until concepts become generally available, we need to emulate them using TMP. +##### Reason + + Until concepts become generally available, we need to emulate them using TMP. Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP. -**Example**: +##### Example template /*requires*/ enable_if, void> @@ -9689,36 +10848,48 @@ Use cases that require concepts (e.g. overloading based on concepts) are among t /*requires*/ enable_if, void> advance(Iter p, int n) { assert(n>=0); while (n--) ++p;} -**Note**: Such code is much simpler using concepts: +##### Note + +Such code is much simpler using concepts: void advance(RandomAccessIterator p, int n) { p += n; } void advance(ForwardIterator p, int n) { assert(n>=0); while (n--) ++p;} -**Enforcement**: ??? +##### Enforcement +??? ### T.122: Use templates (usually template aliases) to compute types at compile time -**Reason**: Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time. +##### Reason -**Note**: "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values. + Template metaprogramming is the only directly supported and half-way principled way of generating types at compile time. -**Example**: +##### Note + +"Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values. + +##### Example ??? big object / small object optimization -**Enforcement**: ??? +##### Enforcement +??? ### T.123: Use `constexpr` functions to compute values at compile time -**Reason**: A function is the most obvious and conventional way of expressing the computation of a value. +##### Reason + + A function is the most obvious and conventional way of expressing the computation of a value. Often a `constexpr` function implies less compile-time overhead than alternatives. -**Note**: "Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values. +##### Note -**Example**: +"Traits" techniques are mostly replaced by template aliases to compute types and `constexpr` functions to compute values. + +##### Example template // requires Number @@ -9731,90 +10902,107 @@ Often a `constexpr` function implies less compile-time overhead than alternative constexpr auto f7 = pow(pi, 7); -**Enforcement**: +##### Enforcement * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions. - ### T.124: Prefer to use standard-library TMP facilities -**Reason**: Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known. +##### Reason -**Example**: + Facilities defined in the standard, such as `conditional`, `enable_if`, and `tuple`, are portable and can be assumed to be known. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.125: If you need to go beyond the standard-library TMP facilities, use an existing library -**Reason**: Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community. +##### Reason + + Getting advanced TMP facilities is not easy and using a library makes you part of a (hopefully supportive) community. Write your own "advanced TMP support" only if you really have to. -**Example**: +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ## Other template rules - ### T.140: Name all nontrivial operations -**Reason**: Documentation, readability, opportunity for reuse. +##### Reason -**Example**: + Documentation, readability, opportunity for reuse. + +##### Example ??? -**Example; good**: +##### Example, good ??? -**Note**: whether functions, lambdas, or operators. +##### Note -**Exceptions**: +whether functions, lambdas, or operators. + +##### Exceptions * Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms. * Lambdas as [initializers](#???) -**Enforcement**: ??? +##### Enforcement +??? ### T.141: Use an unnamed lambda if you need a simple function object in one place only -**Reason**: That makes the code concise and gives better locality than alternatives. +##### Reason -**Example**: + That makes the code concise and gives better locality than alternatives. + +##### Example ??? for-loop equivalent **Exception**: Naming a lambda can be useful for clarity even if it is used only once -**Enforcement**: +##### Enforcement * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas). - ### T.142?: Use template variables to simplify notation -**Reason**: Improved readability. +##### Reason -**Example**: + Improved readability. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### T.143: Don't write unintentionally nongeneric code -**Reason**: Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available. +##### Reason -**Example**: Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering. + Generality. Reusability. Don't gratuitously commit to details; use the most general facilities available. + +##### Example + +Use `!=` instead of `<` to compare iterators; `!=` works for more objects because it doesn't rely on ordering. for(auto i = first; i < last; ++i) { // less generic // ... @@ -9826,7 +11014,9 @@ Write your own "advanced TMP support" only if you really have to. Of course, range-for is better still where it does what you want. -**Example**: Use the least-derived class that has the functionality you need. +##### Example + +Use the least-derived class that has the functionality you need. class base { public: @@ -9854,23 +11044,25 @@ Of course, range-for is better still where it does what you want. use(param.g()); } -**Enforcement**: +##### Enforcement + * Flag comparison of iterators using `<` instead of `!=`. * 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. * Flag functions that take a pointer or reference to a more-derived type but only use functions declared in a base type. - ### T.144: Don't specialize function templates -**Reason**: 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. +##### Reason -**Example**: + 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. + +##### Example ??? **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). -**Enforcement**: +##### Enforcement * Flag all specializations of a function template. Overload instead. @@ -9886,47 +11078,56 @@ C rule summary: * [CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++](#Rcpl-subset) * [CPL.3: If you must use C for interfaces, use C++ in the code using such interfaces](#Rcpl-interface) - ### CPL.1: Prefer C++ to C -**Reason**: C++ provides better type checking and more notational support. +##### Reason + + C++ provides better type checking and more notational support. It provides better support for high-level programming and often generates faster code. -**Example**: +##### Example char ch = 7; void* pv = &ch; int* pi = pv; // not C++ *pi = 999; // overwrite sizeof(int) bytes near &ch -**Enforcement**: Use a C++ compiler. +##### Enforcement +Use a C++ compiler. ### CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++ -**Reason**: That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C." +##### Reason -**Example**: + That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C." + +##### Example int* p1 = malloc(10*sizeof(int)); // not C++ int* p2 = static_cast(malloc(10*sizeof(int))); // not C, C-style C++ int* p3 = new int[10]; // not C int* p4 = (int*)malloc(10*sizeof(int)); // both C and C++ -**Enforcement**: +##### Enforcement * Flag if using a build mode that compiles code as C. * The C++ compiler will enforce that the code is valid C++ unless you use C extension options. - ### CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces -**Reason**: C++ is more expressive than C and offer better support for many types of programming. +##### Reason -**Example**: 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. + C++ is more expressive than C and offer better support for many types of programming. + +##### Example + +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. 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. -**Example**: You can call C from C++: +##### Example + +You can call C from C++: // in C: double sqrt(double); @@ -9936,7 +11137,9 @@ Whenever possible encapsulate the low-level interface in an interface that follo sqrt(2); -**Example**: You can call C++ from C: +##### Example + +You can call C++ from C: // in C: X call_f(struct Y*, int); @@ -9947,8 +11150,9 @@ Whenever possible encapsulate the low-level interface in an interface that follo return p->f(i); // possibly a virtual function call } -**Enforcement**: None needed +##### Enforcement +None needed # SF: Source files @@ -9971,16 +11175,18 @@ Source file rule summary: * [SF.21: Don't use an unnamed (anonymous) namespace in a header](#Rs-unnamed) * [SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities](#Rs-unnamed2) - - ### SF.1: Use a `.cpp` suffix for code files and `.h` for interface files -**Reason**: Convention +##### Reason -**Note**: The specific names `.h` and `.cpp` are not required (but recommended) and other names are in widespread use. + Convention + +##### Note + +The specific names `.h` and `.cpp` are not required (but recommended) and other names are in widespread use. Examples are `.hh` and `.cxx`. Use such names equivalently. -**Example**: +##### Example // foo.h: extern int a; // a declaration @@ -9992,7 +11198,7 @@ Examples are `.hh` and `.cxx`. Use such names equivalently. `foo.h` provides the interface to `foo.cpp`. Global variables are best avoided. -**Example**, bad: +##### Example, bad // foo.h: int a; // a definition @@ -10000,18 +11206,18 @@ Examples are `.hh` and `.cxx`. Use such names equivalently. `#include` twice in a program and you get a linker error for two one-definition-rule violations. - -**Enforcement**: +##### Enforcement * Flag non-conventional file names. * Check that `.h` and `.cpp` (and equivalents) follow the rules below. - ### SF.2: A `.h` file may not contain object definitions or non-inline function definitions -**Reason**: Including entities subject to the one-definition rule leads to linkage errors. +##### Reason -**Example**: + Including entities subject to the one-definition rule leads to linkage errors. + +##### Example ??? @@ -10028,14 +11234,17 @@ Examples are `.hh` and `.cxx`. Use such names equivalently. * `using` alias definitions * ??? -**Enforcement**: Check the positive list above. +##### Enforcement +Check the positive list above. ### SF.3: Use `.h` files for all declarations used in multiple sourcefiles -**Reason**: Maintainability. Readability. +##### Reason -**Example, bad**: + Maintainability. Readability. + +##### Example, bad // bar.cpp: void bar() { cout << "bar\n"; } @@ -10047,16 +11256,17 @@ Examples are `.hh` and `.cxx`. Use such names equivalently. A maintainer of `bar` cannot find all declarations of `bar` if its type needs changing. The user of `bar` cannot know if the interface used is complete and correct. At best, error messages come (late) from the linker. -**Enforcement**: +##### Enforcement * Flag declarations of entities in other source files not placed in a `.h`. - ### SF.4: Include `.h` files before other declarations in a file -**Reason**: Minimize context dependencies and increase readability. +##### Reason -**Example**: + Minimize context dependencies and increase readability. + +##### Example #include #include @@ -10064,7 +11274,7 @@ The user of `bar` cannot know if the interface used is complete and correct. At // ... my code here ... -**Example, bad**: +##### Example, bad #include @@ -10073,18 +11283,23 @@ The user of `bar` cannot know if the interface used is complete and correct. At #include #include -**Note**: This applies to both `.h` and `.cpp` files. +##### Note + +This applies to both `.h` and `.cpp` files. **Exception**: Are there any in good code? -**Enforcement**: Easy. +##### Enforcement +Easy. ### SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface -**Reason** This enables the compiler to do an early consistency check. +##### Reason -**Example**, bad: +This enables the compiler to do an early consistency check. + +##### Example, bad // foo.h: void foo(int); @@ -10098,7 +11313,7 @@ The user of `bar` cannot know if the interface used is complete and correct. At The errors will not be caught until link time for a program calling `bar` or `foobar`. -**Example**: +##### Example // foo.h: void foo(int); @@ -10116,36 +11331,45 @@ The return-type error for `foobar` is now caught immediately when `foo.cpp` is c 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 likelyhood that it is caught earlier by the programmer. -**Enforcement**: ??? +##### Enforcement +??? ### SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### SF.7: Don't put a `using`-directive in a header file -**Reason** Doing so takes away an `#include`r's ability to effectively disambiguate and to use alternatives. +##### Reason -**Example**: +Doing so takes away an `#include`r's ability to effectively disambiguate and to use alternatives. + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### SF.8: Use `#include` guards for all `.h` files -**Reason**: To avoid files being `#include`d several times. +##### Reason -**Example**: + To avoid files being `#include`d several times. + +##### Example // file foobar.h: #ifndef FOOBAR_H @@ -10153,17 +11377,22 @@ but systematic use of `.h` files increases the likelyhood that it is caught earl // ... declarations ... #endif // FOOBAR_H -**Enforcement**: Flag `.h` files without `#include` guards +##### Enforcement +Flag `.h` files without `#include` guards ### SF.9: Avoid cyclic dependencies among source files -**Reason**: Cycles complicates comprehension and slows down compilation. +##### Reason + + Cycles complicates comprehension and slows down compilation. Complicates conversion to use language-supported modules (when they become available). -**Note**: Eliminate cycles; don't just break them with `#include` guards. +##### Note -**Example, bad**: +Eliminate cycles; don't just break them with `#include` guards. + +##### Example, bad // file1.h: #include "file2.h" @@ -10174,49 +11403,55 @@ Complicates conversion to use language-supported modules (when they become avail // file3.h: #include "file1.h" +##### Enforcement -**Enforcement**: Flag all cycles. +Flag all cycles. ### SF.20: Use `namespace`s to express logical structure -**Reason**: ??? +##### Reason -**Example**: + ??? + +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### SF.21: Don't use an unnamed (anonymous) namespace in a header -**Reason**: It is almost always a bug to mention an unnamed namespace in a header file. +##### Reason -**Example**: + It is almost always a bug to mention an unnamed namespace in a header file. + +##### Example ??? -**Enforcement**: +##### Enforcement * Flag any use of an anonymous namespace in a header file. - - ### SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities -**Reason**: +##### Reason + nothing external can depend on an entity in a nested unnamed namespace. Consider putting every definition in an implementation source file should be in an unnamed namespace unless that is defining an "external/exported" entity. -**Example**: 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. +##### Example + +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. ??? -**Enforcement**: +##### Enforcement * ??? - # SL: The Standard Library Using only the bare language, every task is tedious (in any language). @@ -10228,10 +11463,11 @@ Standard-library rule summary: * [SL.2: Prefer the standard library to other libraries](#Rsl-sl) * ??? - ### SL.1: Use libraries wherever possible -**Reason**: Save time. Don't re-invent the wheel. +##### Reason + + Save time. Don't re-invent the wheel. Don't replicate the work of others. Benefit from other people's work when they make improvements. Help other people when you make improvements. @@ -10240,7 +11476,9 @@ Help other people when you make improvements. ### SL.2: Prefer the standard library to other libraries -**Reason**. More people know the standard library. +##### Reason + +More people know the standard library. It is more likely to be stable, well-maintained, and widely available than your own code or most other libraries. ## SL.con: Containers @@ -10474,26 +11712,28 @@ The following are under consideration but not yet in the rules below, and may be An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic. - ### Type.1: Don't use `reinterpret_cast`. -**Reason**: +##### Reason + 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`. -**Example; bad**: +##### Example, bad std::string s = "hello world"; double* p = reinterpret_cast(&s); // BAD -**Enforcement**: Issue a diagnostic for any use of `reinterpret_cast`. To fix: Consider using a `variant` instead. +##### Enforcement +Issue a diagnostic for any use of `reinterpret_cast`. To fix: Consider using a `variant` instead. ### Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead. -**Reason**: +##### Reason + 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`. -**Example; bad**: +##### Example, bad class base { public: virtual ~base() =0; }; @@ -10511,15 +11751,17 @@ Use of these casts can violate type safety and cause the program to access a var derived2* p2 = static_cast(p); // BAD, tries to treat d1 as a derived2, which it is not cout << p2.get_s(); // tries to access d1's nonexistent string member, instead sees arbitrary bytes near d1 -**Enforcement**: 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. +##### Enforcement +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. ### Type.3: Don't use `const_cast` to cast away `const` (i.e., at all). -**Reason**: +##### Reason + Casting away `const` is a lie. If the variable is actually declared `const`, it's a lie punishable by undefined behavior. -**Example; bad**: +##### Example, bad void f(const int& i) { const_cast(i) = 42; // BAD @@ -10531,19 +11773,20 @@ Casting away `const` is a lie. If the variable is actually declared `const`, it' f(i); // silent side effect f(j); // undefined behavior - **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. -**Enforcement**: 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`. +##### Enforcement +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`. ### Type.4: Don't use C-style `(T)expression` casts that would perform a `static_cast` downcast, `const_cast`, or `reinterpret_cast`. -**Reason**: +##### Reason + 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`. 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. -**Example; bad**: +##### Example, bad std::string s = "hello world"; double* p = (double*)(&s); // BAD @@ -10574,22 +11817,21 @@ Note that a C-style `(T)expression` cast means to perform the first of the follo f(i); // silent side effect f(j); // undefined behavior -**Enforcement**: 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. - +##### Enforcement +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. ### Type.5: Don't use a variable before it has been initialized. [ES.20: Always initialize an object](#Res-always) is required. - - ### Type.6: Always initialize a member variable. -**Reason**: +##### Reason + 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. -**Example**: +##### Example struct X { int i; }; @@ -10599,17 +11841,18 @@ Before a variable has been initialized, it does not contain a deterministic vali X x2{}; // GOOD use(x2); -**Enforcement**: +##### Enforcement * 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. * Issue a diagnostic when constructing an object of a trivially constructible type without `()` or `{}` to initialize its members. To fix: Add `()` or `{}`. ### Type.7: Avoid accessing members of raw unions. Prefer `variant` instead. -**Reason**: +##### Reason + 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. -**Example**: +##### Example union U { int i; double d; }; @@ -10624,16 +11867,17 @@ Reading from a union member assumes that member was the last one written, and wr 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. -**Enforcement**: +##### Enforcement * Issue a diagnostic for accessing a member of a union. To fix: Use a `variant` instead. ### Type.8: Avoid reading from varargs or passing vararg arguments. Prefer variadic template parameters instead. -**Reason**: +##### Reason + 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. -**Example**: +##### Example int sum(...) { // ... @@ -10655,7 +11899,7 @@ Reading from a vararg assumes that the correct type was actually passed. Passing 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. -**Enforcement**: +##### Enforcement * Issue a diagnostic for using `va_list`, `va_start`, or `va_arg`. To fix: Use a variadic template parameter list instead. * Issue a diagnostic for passing an argument to a vararg parameter. To fix: Use a different function, or `[[suppress(types)]]`. @@ -10672,13 +11916,13 @@ The following are under consideration but not yet in the rules below, and may be An implementation of this profile shall recognize the following patterns in source code as non-conforming and issue a diagnostic. - ### Bounds.1: Don't use pointer arithmetic. Use `array_view` instead. -**Reason**: +##### Reason + 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. -**Example; bad**: +##### Example, bad void f(int* p, int count) { @@ -10702,7 +11946,7 @@ Pointers should only refer to single objects, and pointer arithmetic is fragile use(&p[0], 3); // BAD } -**Example; good**: +##### Example, good void f(array_view a) // BETTER: use array_view in the function declaration { @@ -10721,16 +11965,17 @@ Pointers should only refer to single objects, and pointer arithmetic is fragile use(a.data(), 3); // OK } -**Enforcement**: -Issue a diagnostic for any arithmetic operation on an expression of pointer type that results in a value of pointer type. +##### Enforcement +Issue a diagnostic for any arithmetic operation on an expression of pointer type that results in a value of pointer type. ### Bounds.2: Only index into arrays using constant expressions. -**Reason**: +##### Reason + 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. -**Example; bad**: +##### Example, bad void f(array a, int pos) { @@ -10740,7 +11985,7 @@ Dynamic accesses into arrays are difficult for both tools and humans to validate a[10] = 4; // BAD - no replacement, just don't do this } -**Example; good**: +##### Example, good // ALTERNATIVE A: Use an array_view @@ -10766,7 +12011,7 @@ Dynamic accesses into arrays are difficult for both tools and humans to validate at(a, pos-1) = 2; // OK } -**Example; bad**: +##### Example, bad void f() { @@ -10775,7 +12020,7 @@ Dynamic accesses into arrays are difficult for both tools and humans to validate arr[i] = i; // BAD, cannot use non-constant indexer } -**Example; good**: +##### Example, good // ALTERNATIVE A: Use an array_view void f1() @@ -10794,8 +12039,8 @@ Dynamic accesses into arrays are difficult for both tools and humans to validate at(arr, i) = i; } +##### Enforcement -**Enforcement**: 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. 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. @@ -10810,13 +12055,13 @@ Issue a diagnostic for any indexing expression on an expression or variable of a at(a, i + j) = 12; // OK - bounds-checked } - ### Bounds.3: No array-to-pointer decay. -**Reason**: +##### Reason + Pointers should not be used as arrays. `array_view` is a bounds-checked, safe alternative to using pointers to access arrays. -**Example; bad**: +##### Example, bad void g(int* p, size_t length); @@ -10827,7 +12072,7 @@ Pointers should not be used as arrays. `array_view` is a bounds-checked, safe al g(&a[0], 1); // OK } -**Example; good**: +##### Example, good void g(int* p, size_t length); void g1(array_view av); // BETTER: get g() changed. @@ -10841,16 +12086,17 @@ Pointers should not be used as arrays. `array_view` is a bounds-checked, safe al g1(a); // OK - no decay here, instead use implicit array_view ctor } -**Enforcement**: -Issue a diagnostic for any expression that would rely on implicit conversion of an array type to a pointer type. +##### Enforcement +Issue a diagnostic for any expression that would rely on implicit conversion of an array type to a pointer type. ### Bounds.4: Don't use standard library functions and types that are not bounds-checked. -**Reason**: +##### Reason + 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()`. -**Example; bad**: +##### Example, bad void f() { @@ -10859,7 +12105,7 @@ These functions all have bounds-safe overloads that take `array_view`. Standard memcmp(a.data(), b.data(), 10); // BAD, and contains a length error } -**Example; good**: +##### Example, good void f() { @@ -10868,7 +12114,9 @@ These functions all have bounds-safe overloads that take `array_view`. Standard memcmp({a, b}); // OK } -**Example**: 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. +##### Example + +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. void f(std::vector& v, std::array a, int i) { @@ -10881,7 +12129,7 @@ These functions all have bounds-safe overloads that take `array_view`. Standard v.at(0) = at(a, i); // OK (alternative 2) } -**Enforcement**: +##### Enforcement * Issue a diagnostic for any call to a standard library function that is not bounds-checked. ??? insert link to a list of banned functions @@ -11057,22 +12305,27 @@ More specific and detailed rules are easier to enforce. ### NL.1: Don't say in comments what can be clearly stated in code -**Reason**: Compilers do not read comments. +##### Reason + + Compilers do not read comments. Comments are less precise than code. Comments are not updated as consistently as code. -**Example, bad**: +##### Example, bad auto x = m*v1 + vv; // multiply m with v1 and add the result to vv -**Enforcement**: Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++. +##### Enforcement +Build an AI program that interprets colloquial English text and see if what is said could be better expressed in C++. ### NL.2: State intent in comments -**Reason**: Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation. +##### Reason -**Example**: + Code says what is done, not what is supposed to be done. Often intent can be stated more clearly and concisely than the implementation. + +##### Example void stable_sort(Sortable& c) // sort c in the order determined by <, keep equal elements (as defined by ==) in their original relative order @@ -11080,29 +12333,36 @@ Comments are not updated as consistently as code. // ... quite a few lines of non-trivial code ... } -**Note**: If the comment and the code disagrees, both are likely to be wrong. +##### Note +If the comment and the code disagrees, both are likely to be wrong. ### NL.3: Keep comments crisp -**Reason**: Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file. +##### Reason -**Enforcement**: not possible. + Verbosity slows down understanding and makes the code harder to read by spreading it around in the source file. +##### Enforcement + +not possible. ### NL.4: Maintain a consistent indentation style -**Reason**: Readability. Avoidance of "silly mistakes." +##### Reason -**Example, bad**: + Readability. Avoidance of "silly mistakes." + +##### Example, bad int i; for (i=0; i NL.5 Don't encode type information in names @@ -11110,11 +12370,13 @@ Comments are not updated as consistently as code. Names with types encoded are either verbose or cryptic. Hungarian notation is evil (at least in a strongly statically-typed language). -**Example**: +##### Example ??? -**Note**: Some styles distinguishes members from local variable, and/or from global variable. +##### Note + +Some styles distinguishes members from local variable, and/or from global variable. struct S { int m_; @@ -11123,7 +12385,9 @@ Hungarian notation is evil (at least in a strongly statically-typed language). This is not evil. -**Note**: Some styles distinguishes types from non-types. +##### Note + +Some styles distinguishes types from non-types. typename class Hash_tbl { // maps string to T @@ -11139,21 +12403,26 @@ This is not evil. **Rationale**: ??? -**Example**: +##### Example ??? -**Enforcement**: ??? +##### Enforcement +??? ### NL.8: Use a consistent naming style **Rationale**: Consistence in naming and naming style increases readability. -**Note**: Where are many styles and when you use multiple libraries, you can't follow all their differences conventions. +##### Note + +Where are many styles and when you use multiple libraries, you can't follow all their differences conventions. Choose a "house style", but leave "imported" libraries with their original style. -**Example**, ISO Standard, use lower case only and digits, separate words with underscores: +##### Example + +ISO Standard, use lower case only and digits, separate words with underscores: * `int` * `vector` @@ -11161,14 +12430,18 @@ Choose a "house style", but leave "imported" libraries with their original style Avoid double underscores `__` -**Example**: [Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf): +##### Example + +[Stroustrup](http://www.stroustrup.com/Programming/PPP-style.pdf): ISO Standard, but with upper case used for your own types and concepts: * `int` * `vector` * `My_map` -**Example**: CamelCase: capitalize each word in a multi-word identifier +##### Example + +CamelCase: capitalize each word in a multi-word identifier * `int` * `vector` @@ -11177,28 +12450,34 @@ ISO Standard, but with upper case used for your own types and concepts: Some conventions capitalize the first letter, some don't. -**Note**: Try to be consistent in your use of acronyms, lengths of identifiers: +##### Note + +Try to be consistent in your use of acronyms, lengths of identifiers: int mtbf {12}; int mean_time_between_failor {12}; // make up your mind -**Enforcement**: Would be possible except for the use of libraries with varying conventions. - +##### Enforcement +Would be possible except for the use of libraries with varying conventions. ### NL 9: Use ALL_CAPS for macro names only -**Reason**: To avoid confusing macros from names that obeys scope and type rules +##### Reason -**Example**: + To avoid confusing macros from names that obeys scope and type rules + +##### Example ??? -**Note**: This rule applies to non-macro symbolic constants +##### Note + +This rule applies to non-macro symbolic constants enum bad { BAD, WORSE, HORRIBLE }; // BAD -**Enforcement**: +##### Enforcement * Flag macros with lower-case letters * Flag ALL_CAPS non-macro names @@ -11207,21 +12486,26 @@ Some conventions capitalize the first letter, some don't. ### NL.10: Avoid CamelCase -**Reason**: The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ standard library. +##### Reason + + The use of underscores to separate parts of a name is the original C and C++ style and used in the C++ standard library. If you prefer CamelCase, you have to choose among different flavors of camelCase. -**Example**: +##### Example ??? -**Enforcement**: Impossible. +##### Enforcement +Impossible. ### NL.15: Use spaces sparingly -**Reason**: Too much space makes the text larger and distracts. +##### Reason -**Example, bad**: + Too much space makes the text larger and distracts. + +##### Example, bad #include < map > @@ -11230,7 +12514,7 @@ If you prefer CamelCase, you have to choose among different flavors of camelCase // ... } -**Example**: +##### Example #include @@ -11239,15 +12523,21 @@ If you prefer CamelCase, you have to choose among different flavors of camelCase // ... } -**Note**: Some IDEs have their own opinions and adds distracting space. +##### Note -**Note**: We value well-placed whitespace as a significant help for readability. Just don't overdo it. +Some IDEs have their own opinions and adds distracting space. + +##### Note + +We value well-placed whitespace as a significant help for readability. Just don't overdo it. ### NL.16: Use a conventional class member declaration order -**Reason**: A conventional order of members improves readability. +##### Reason + + A conventional order of members improves readability. When declaring a class use the following order @@ -11260,20 +12550,25 @@ Used the `public` before `protected` before `private` order. Private types and functions can be placed with private data. -**Example**: +##### Example ??? -**Enforcement**: Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule. +##### Enforcement +Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule. ### NL.17: Use K&R-derived layout -**Reason**: This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes well). +##### Reason -**Note**: In the context of C++, this style is often called "Stroustrup". + This is the original C and C++ layout. It preserves vertical space well. It distinguishes different language constructs (such as functions and classes well). -**Example**: +##### Note + +In the context of C++, this style is often called "Stroustrup". + +##### Example struct Cable { int x; @@ -11309,34 +12604,44 @@ Private types and functions can be placed with private data. return some_value; } -**Note**: a space between `if` and `(` +**Note** a space between `if` and `(` -**Note**: Use separate lines for each statement, the branches of an `if`, and the body of a `for`. +##### Note -**Note** the `{` for a `class` and a `struct` in *not* on a separate line, but the `{` for a function is. +Use separate lines for each statement, the branches of an `if`, and the body of a `for`. -**Note**: Capitalize the names of your user-defined types to distinguish them from standards-library types. +##### Note -**Note**: Do not capitalize function names. +The `{` for a `class` and a `struct` in *not* on a separate line, but the `{` for a function is. -**Enforcement**: If you want enforcement, use an IDE to reformat. +##### Note +Capitalize the names of your user-defined types to distinguish them from standards-library types. + +##### Note + +Do not capitalize function names. + +##### Enforcement + +If you want enforcement, use an IDE to reformat. ### NL.18: Use C++-style declarator layout -**Reason**: The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types. +##### Reason + + The C-style layout emphasizes use in expressions and grammar, whereas the C++-style emphasizes types. The use in expressions argument doesn't hold for references. -**Example**: +##### Example T& operator[](size_t); // OK T &operator[](size_t); // just strange T & operator[](size_t); // undecided -**Enforcement**: Impossible in the face of history. - - +##### Enforcement +Impossible in the face of history. # FAQ: Answers to frequently asked questions @@ -11591,7 +12896,9 @@ In summary, no post-construction technique is perfect. The worst techniques dodg 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. -**Example**: 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`: +##### Example + +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`: ``` class base { @@ -11624,7 +12931,9 @@ template class customizable : Policy { /*...*/ }; // note: private inheritance ``` -**Note**: This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles. +##### Note + +This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles. For a base class `Base`, calling code might try to destroy derived objects through pointers to `Base`, such as when using a `shared_ptr`. 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. @@ -11641,7 +12950,9 @@ Note that the NVI pattern cannot be applied to the destructor because constructo 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. -**Exception**: 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. +##### Exception + +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. Consider also this rare case: @@ -11667,7 +12978,7 @@ In general, however, avoid concrete base classes (see Item 35). For example, `un 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. -**Example**: +##### Example ``` class nefarious { @@ -11729,7 +13040,9 @@ std::vector vec(10); // this is line can std::terminate() 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. -**Note**: 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. +##### Note + +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. Consider the following advice and requirements found in the C++ Standard: @@ -11761,15 +13074,19 @@ When using exceptions as your error handling mechanism, always document this beh ## Define Copy, move, and destroy consistently -**Reason**: ??? +##### Reason + ??? -**Note**: If you define a copy constructor, you must also define a copy assignment operator. +##### Note -**Note**: If you define a move constructor, you must also define a move assignment operator. +If you define a copy constructor, you must also define a copy assignment operator. +##### Note -**Example**: +If you define a move constructor, you must also define a move assignment operator. + +##### Example class x { // ... @@ -11825,7 +13142,10 @@ If you define copying, and any base or member has a type that defines a move ope If you define any of the copy constructor, copy assignment operator, or destructor, you probably should define the others. -**Note**: 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: +##### Note + + +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: * 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.) * 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. @@ -11854,15 +13174,15 @@ Resource management rule summary: * [If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations](#Cr-handle) * [If a class is a container, give it an initializer-list constructor](#Cr-list) - - ### Provide strong resource safety; that is, never leak anything that you think of as a resource -**Reason**: Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations. +##### Reason + + Prevent leaks. Leaks can lead to performance degradation, mysterious error, system crashes, and security violations. **Alternative formulation**: Have every resource represented as an object of some class managing its lifetime. -**Example**: +##### Example template class Vector { @@ -11874,18 +13194,21 @@ Resource management rule summary: 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.). -**Example**: +##### Example ??? "odd" non-memory resource ??? -**Enforcement**: 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. +##### Enforcement +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. ### Never throw while holding a resource not owned by a handle -**Reason**: That would be a leak. +##### Reason -**Example**: + That would be a leak. + +##### Example void f(int i) { @@ -11909,24 +13232,30 @@ If `i==0` the file handle for `a file` is leaked. On the other hand, the `ifstre The code is simpler as well as correct. -**Enforcement**: A checker must consider all "naked pointers" suspicious. +##### Enforcement + +A checker must consider all "naked pointers" suspicious. A checker probably must rely on a human-provided list of resources. For starters, we know about the standard-library containers, `string`, and smart pointers. The use of `array_view` and `string_view` should help a lot (they are not resource handles). - ### A "raw" pointer or reference is never a resource handle -**Reason** To be able to distinguish owners from views. +##### Reason -**Note**: This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr` and `Range` are not owners. +To be able to distinguish owners from views. +##### Note + +This is independent of how you "spell" pointer: `T*`, `T&`, `Ptr` and `Range` are not owners. ### Never let a pointer outlive the object it points to -**Reason**: To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system. +##### Reason -**Example**: + To avoid extremely hard-to-find errors. Dereferencing such a pointer is undefined behavior and could lead to violations of the type system. + +##### Example string* bad() // really bad { @@ -11944,14 +13273,17 @@ The use of `array_view` and `string_view` should help a lot (they are not resour 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. -**Enforcement**: 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. +##### Enforcement +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. ### Use templates to express containers (and other resource handles) -**Reason**: To provide statically type-safe manipulation of elements. +##### Reason -**Example**: + To provide statically type-safe manipulation of elements. + +##### Example template class Vvector { // ... @@ -11961,28 +13293,35 @@ The `string`s of `v` are destroyed upon exit from `bad()` and so is `v` itself. ### Return containers by value (relying on move for efficiency) -**Reason**: To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime. +##### Reason -**Example**: + To simplify code and eliminate a need for explicit memory management. To bring an object into a surrounding scope, thereby extending its lifetime. + +##### Example ??? vector -**Example**: +##### Example ??? factory -**Enforcement**: Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`). +##### Enforcement +Check for pointers and references returned from functions and see if they are assigned to resource handles (e.g., to a `unique_ptr`). ### If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations -**Reason**: To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource. +##### Reason -**Example**: + To provide complete control of the lifetime of the resource. To provide a coherent set of operations on the resource. + +##### Example ??? Messing with pointers -**Note**: If all members are resource handles, rely on the default special operations where possible. +##### Note + +If all members are resource handles, rely on the default special operations where possible. template struct Named { string name; @@ -11991,14 +13330,17 @@ The `string`s of `v` are destroyed upon exit from `bad()` and so is `v` itself. Now `Named` has a default constructor, a destructor, and efficient copy and move operations, provided `T` has. -**Enforcement**: 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. +##### Enforcement +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. ### If a class is a container, give it an initializer-list constructor -**Reason**: It is common to need an initial set of elements. +##### Reason -**Example**: + It is common to need an initial set of elements. + +##### Example template class Vector { public: @@ -12008,8 +13350,9 @@ Now `Named` has a default constructor, a destructor, and efficient copy and move Vector vs = { "Nygaard", "Ritchie" }; -**Enforcement**: When is a class a container? +##### Enforcement + When is a class a container? # To-do: Unclassified proto-rules