diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index dd77c91..075e11d 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -1,4 +1,4 @@ -# C++ Core Guidelines +# C++ Core Guidelines December 28, 2015 @@ -90,7 +90,7 @@ Definitions of terms used to express and discuss the rules, that are not languag * resource * exception guarantee -# Abstract +# Abstract This document is a set of guidelines for using C++ well. The aim of this document is to help people to use modern C++ effectively. @@ -128,7 +128,7 @@ We plan to build tools for that and hope others will too. Comments and suggestions for improvements are most welcome. We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve. -# In: Introduction +# In: Introduction This is a set of core guidelines for modern C++, C++14, and taking likely future enhancements and taking ISO Technical Specifications (TSs) into account. The aim is to help C++ programmers to write simpler, more efficient, more maintainable code. @@ -142,11 +142,11 @@ Introduction summary: * [In.struct: The structure of this document](#SS-struct) * [In.sec: Major sections](#SS-sec) -## In.target: Target readership +## In.target: Target readership All C++ programmers. This includes [programmers who might consider C](#S-cpl). -## In.aims: Aims +## In.aims: Aims The purpose of this document is to help developers to adopt modern C++ (C++11, C++14, and soon C++17) and to achieve a more uniform style across code bases. @@ -155,7 +155,7 @@ As far as we can tell, these rules lead to code that performs as well or better Consider these rules ideals for new code, opportunities to exploit when working on older code, and try to approximate these ideas as closely as feasible. Remember: -### In.0: Don't panic! +### In.0: Don't panic! Take the time to understand the implications of a guideline rule on your program. @@ -185,7 +185,7 @@ Some rules aim to increase various forms of safety while others aim to reduce th The guidelines aimed at preventing accidents often ban perfectly legal C++. However, when there are two ways of expressing an idea and one has shown itself a common source of errors and the other has not, we try to guide programmers towards the latter. -## In.not: Non-aims +## In.not: Non-aims The rules are not intended to be minimal or orthogonal. In particular, general rules can be simple, but unenforceable. @@ -220,7 +220,7 @@ The rules are not value-neutral. They are meant to make code simpler and more correct/safer than most existing C++ code, without loss of performance. They are meant to inhibit perfectly valid C++ code that correlates with errors, spurious complexity, and poor performance. -## In.force: Enforcement +## In.force: Enforcement Rules with no enforcement are unmanageable for large code bases. Enforcement of all rules is possible only for a small weak set of rules or for a specific user community. @@ -258,7 +258,7 @@ where "tag" is the anchor name of the item where the Enforcement rule appears (e name of a profile group-of-rules ("type", "bounds", or "lifetime"), or a specific rule in a profile ("type.4", or "bounds.2"). -## In.struct: The structure of this document +## In.struct: The structure of this document Each rule (guideline, suggestion) can have several parts: @@ -289,7 +289,7 @@ This is not a language manual. It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code. Recommended information sources can be found in [the references](#S-references). -## In.sec: Major sections +## In.sec: Major sections * [In: Introduction](#S-introduction) * [P: Philosophy](#S-philosophy) @@ -327,7 +327,7 @@ These sections are not orthogonal. Each section (e.g., "P" for "Philosophy") and each subsection (e.g., "C.hier" for "Class Hierarchies (OOP)") have an abbreviation for ease of searching and reference. The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular"). -# P: Philosophy +# P: Philosophy The rules in this section are very general. @@ -347,7 +347,7 @@ Philosophical rules are generally not mechanically checkable. However, individual rules reflecting these philosophical themes are. Without a philosophical basis the more concrete/specific/checkable rules lack rationale. -### P.1: Express ideas directly in code +### P.1: Express ideas directly in code ##### Reason @@ -425,7 +425,7 @@ Very hard in general. * flag uses of casts (casts neuter the type system) * detect code that mimics the standard library (hard) -### P.2: Write in ISO Standard C++ +### P.2: Write in ISO Standard C++ ##### Reason @@ -451,7 +451,7 @@ In such cases, control their (dis)use with an extension of these Coding Guidelin 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 +### P.3: Express intent ##### Reason @@ -514,7 +514,7 @@ Look for common patterns for which there are better alternatives There is a huge scope for cleverness and semi-automated program transformation. -### P.4: Ideally, a program should be statically type safe +### P.4: Ideally, a program should be statically type safe ##### Reason @@ -544,7 +544,7 @@ For example: * range errors - use `span` * 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 +### P.5: Prefer compile-time checking to run-time checking ##### Reason @@ -581,7 +581,7 @@ Code clarity and performance. You don't need to write error handlers for errors * 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 +### P.6: What cannot be checked at compile time should be checkable at run time ##### Reason @@ -684,7 +684,7 @@ How do we transfer both ownership and all information needed for validating use? * Flag (pointer, count)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons) * ??? -### P.7: Catch run-time errors early +### P.7: Catch run-time errors early ##### Reason @@ -802,7 +802,7 @@ 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 resources +### P.8: Don't leak any resources ##### Reason @@ -848,7 +848,7 @@ if they can be cleanly and safely de-allocated, they should be.) * 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 +### P.9: Don't waste time or space ##### Reason @@ -911,7 +911,7 @@ After that, we can look at waste related to algorithms and requirements, but tha Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste. -# I: Interfaces +# I: Interfaces An interface is a contract between two parts of a program. Precisely stating what is expected of a supplier of a service and a user of that service is essential. Having good (easy-to-understand, encouraging efficient use, not error-prone, supporting testing, etc.) interfaces is probably the most important single aspect of code organization. @@ -947,7 +947,7 @@ See also * [E: Error handling](#S-errors) * [T: Templates and generic programming](#S-templates) -### I.1: Make interfaces explicit +### I.1: Make interfaces explicit ##### Reason @@ -988,7 +988,7 @@ Functions can be template functions and sets of functions can be classes or clas * (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 +### I.2 Avoid global variables ##### Reason @@ -1036,7 +1036,7 @@ You cannot have a race condition on immutable data. (Simple) Report all non-`const` variables declared at namespace scope. -### I.3: Avoid singletons +### I.3: Avoid singletons ##### Reason @@ -1080,7 +1080,7 @@ Very hard in general. * Look for classes for which only a single object is created (by counting objects or by examining constructors). * If a class X has a public static function that contains a function-local static of the class' type X and returns a pointer or reference to it, ban that. -### I.4: Make interfaces precisely and strongly typed +### I.4: Make interfaces precisely and strongly typed ##### Reason @@ -1175,7 +1175,7 @@ The function can also be written in such a way that it will accept any time dura * (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) +### I.5: State preconditions (if any) ##### Reason @@ -1216,7 +1216,7 @@ We don't need to mention it for each member function. **See also**: The rules for passing pointers. ??? -### I.6: Prefer `Expects()` for expressing preconditions +### I.6: Prefer `Expects()` for expressing preconditions ##### Reason @@ -1247,7 +1247,7 @@ Preconditions should be part of the interface rather than part of the implementa (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 +### I.7: State postconditions ##### Reason @@ -1343,7 +1343,7 @@ Postconditions related only to internal state belongs in the definition/implemen directly in the general case. Domain specific checkers (like lock-holding checkers) exist for many toolchains. -### I.8: Prefer `Ensures()` for expressing postconditions +### I.8: Prefer `Ensures()` for expressing postconditions ##### Reason @@ -1371,7 +1371,7 @@ Ideally, that `Ensures` should be part of the interface, but that's not easily d (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 +### I.9: If an interface is a template, document its parameters using concepts ##### Reason @@ -1398,7 +1398,7 @@ Soon (maybe in 2016), most compilers will be able to check `requires` clauses on (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 +### I.10: Use exceptions to signal a failure to perform a required task ##### Reason @@ -1448,7 +1448,7 @@ We don't consider "performance" a valid reason not to use exceptions. * (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*`) +### I.11: Never transfer ownership by a raw pointer (`T*`) ##### Reason @@ -1510,7 +1510,7 @@ so the default is "no ownership transfer." * (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path. * (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer. -### I.12: Declare a pointer that must not be null as `not_null` +### I.12: Declare a pointer that must not be null as `not_null` ##### Reason @@ -1542,7 +1542,7 @@ Note: `length()` is, of course, `std::strlen()` in disguise. * (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 +### I.13: Do not pass an array as a single pointer ##### Reason @@ -1596,7 +1596,7 @@ This `draw2()` passes the same amount of information to `draw()`, but makes the * (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.22: Avoid complex initialization of global objects +### I.22: Avoid complex initialization of global objects ##### Reason @@ -1630,7 +1630,7 @@ It is usually best to avoid global (namespace scope) objects altogether. * Flag initializers of globals that call non-`constexpr` functions * Flag initializers of globals that access `extern` objects -### I.23: Keep the number of function arguments low +### I.23: Keep the number of function arguments low ##### Reason @@ -1675,7 +1675,7 @@ There are functions that are best expressed with four individual arguments, but * 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.24: Avoid adjacent unrelated parameters of the same type +### I.24: Avoid adjacent unrelated parameters of the same type ##### Reason @@ -1723,7 +1723,7 @@ are often filled in by name at the call site. (Simple) Warn if two consecutive parameters share the same type. -### I.25: Prefer abstract classes as interfaces to class hierarchies +### I.25: Prefer abstract classes as interfaces to class hierarchies ##### Reason @@ -1760,7 +1760,7 @@ This will force every derived class to compute a center -- even if that's non-tr (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.26: If you want a cross-compiler ABI, use a C-style subset +### I.26: If you want a cross-compiler ABI, use a C-style subset ##### Reason @@ -1778,7 +1778,7 @@ If you use a single compiler, you can use full C++ in interfaces. That may requi (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI. -# F: Functions +# F: Functions A function specifies an action or a computation that takes the system from one consistent state to the next. It is the fundamental building block of programs. @@ -1835,11 +1835,11 @@ Other function rules: Functions have strong similarities to lambdas and function objects so see also Section ???. -## F.def: Function definitions +## F.def: Function definitions A function definition is a function declaration that also specifies the function's implementation, the function body. -### F.1: "Package" meaningful operations as carefully named functions +### F.1: "Package" meaningful operations as carefully named functions ##### Reason @@ -1890,7 +1890,7 @@ Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unl * See [Keep functions short](#Rf-single) * Flag identical and very similar lambdas used in different places. -### F.2: A function should perform a single logical operation +### F.2: A function should perform a single logical operation ##### Reason @@ -1950,7 +1950,7 @@ If there was a need, we could further templatize `read()` and `print()` on the d * 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 +### F.3: Keep functions short and simple ##### Reason @@ -2031,7 +2031,7 @@ Small simple functions are easily inlined where the cost of a function call is s * Flag functions that are too complex. How complex is too complex? You could use cyclomatic complexity. Try "more than 10 logical path through." Count a simple switch as one path. -### F.4: If a function may have to be evaluated at compile time, declare it `constexpr` +### F.4: If a function may have to be evaluated at compile time, declare it `constexpr` ##### Reason @@ -2096,7 +2096,7 @@ API will have to be refactored or drop `constexpr`. Impossible and unnecessary. The compiler gives an error if a non-`constexpr` function is called where a constant is required. -### F.5: If a function is very small and time critical, declare it `inline` +### F.5: If a function is very small and time critical, declare it `inline` ##### Reason @@ -2123,7 +2123,7 @@ Member functions defined in-class are `inline` by default. 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` +### F.6: If your function may not throw, declare it `noexcept` ##### Reason @@ -2184,7 +2184,7 @@ Destructors, `swap` functions, move operations, and default constructors should * 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 +### F.7: For general use, take `T*` arguments rather than smart pointers ##### Reason @@ -2210,7 +2210,7 @@ We can catch dangling pointers statically, so we don't need to rely on resource Flag smart pointer arguments. -### F.8: Prefer pure functions +### F.8: Prefer pure functions ##### Reason @@ -2229,12 +2229,12 @@ Pure functions are easier to reason about, sometimes easier to optimize (and eve Not possible. -## F.call: Parameter passing +## F.call: Parameter passing There are a variety of ways to pass parameters to a function and to return values. -### F.15: Prefer simple and conventional ways of passing information +### F.15: Prefer simple and conventional ways of passing information ##### Reason @@ -2249,7 +2249,7 @@ The following tables summarize the advice in the following Guidelines, F.16-21. -### F.16: For "in" parameters, pass cheaply copied types by value and others by reference to `const` +### F.16: For "in" parameters, pass cheaply copied types by value and others by reference to `const` ##### Reason @@ -2317,7 +2317,7 @@ If you need the notion of an optional value, use a pointer, `std::optional`, or * (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference is `move`d. -### F.17: For "in-out" parameters, pass by reference to non-`const` +### F.17: For "in-out" parameters, pass by reference to non-`const` ##### Reason @@ -2352,7 +2352,7 @@ If the writer of `g()` makes an assumption about the size of `buffer` a bad logi * (Simple) ((Foundation)) Warn when a non-`const` parameter being passed by reference is `move`d. -### F.18: For "consume" parameters, pass by `X&&` and `std::move` the parameter +### F.18: For "consume" parameters, pass by `X&&` and `std::move` the parameter ##### Reason @@ -2368,7 +2368,7 @@ Unique owner types that are move-only and cheap-to-move, such as `unique_ptr`, c * Don't conditionally move from objects -### F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter +### F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter ##### Reason @@ -2388,7 +2388,7 @@ In that case, and only that case, make the parameter `TP&&` where `TP` is a temp * Flag a function that takes a `TP&&` parameter (where `TP` is a template type parameter name) and does anything with it other than `std::forward`ing it exactly once on every static path. -### F.20: For "out" output values, prefer return values to output parameters +### F.20: For "out" output values, prefer return values to output parameters ##### Reason @@ -2434,7 +2434,7 @@ It is not recommended to return a `const` value. Such older advice is now obsole * Flag returning a `const` value. To fix: Remove `const` to return a non-`const` value instead. -### F.21: To return multiple "out" values, prefer returning a tuple or struct +### F.21: To return multiple "out" values, prefer returning a tuple or struct ##### Reason @@ -2488,7 +2488,7 @@ In some cases it may be useful to return a specific, user-defined `Value_or_erro An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`. -### F.22: Use `T*` or `owner` to designate a single object +### F.22: Use `T*` or `owner` to designate a single object ##### Reason @@ -2532,7 +2532,7 @@ A `not_null` is assumed not to be the `nullptr`; a `T*` may be the `nullptr` * (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. -### F.23: Use a `not_null` to indicate that "null" is not a valid value +### F.23: Use a `not_null` to indicate that "null" is not a valid value ##### Reason @@ -2559,7 +2559,7 @@ Clarity. A function with a `not_null` parameter makes it clear that the calle * (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.24: Use a `span` or a `span_p` to designate a half-open sequence +### F.24: Use a `span` or a `span_p` to designate a half-open sequence ##### Reason @@ -2591,7 +2591,7 @@ Passing a `span` object as an argument is exactly as efficient as passing a pair (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `span` instead. -### F.25: Use a `zstring` or a `not_null` to designate a C-style string +### F.25: Use a `zstring` or a `not_null` to designate a C-style string ##### Reason @@ -2617,7 +2617,7 @@ When I call `length(s)` should I test for `s == nullptr` first? Should the imple **See also**: [Support library](#S-gsl). -### F.26: Use a `unique_ptr` to transfer ownership where a pointer is needed +### F.26: Use a `unique_ptr` to transfer ownership where a pointer is needed ##### Reason @@ -2645,7 +2645,7 @@ You need to pass a pointer rather than an object if what you are transferring is (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 +### F.27: Use a `shared_ptr` to share ownership ##### Reason @@ -2677,7 +2677,7 @@ Note that pervasive use of `shared_ptr` has a cost (atomic operations on the `sh (Not enforceable) This is a too complex pattern to reliably detect. -### F.42: Return a `T*` to indicate a position (only) +### F.42: Return a `T*` to indicate a position (only) ##### Reason @@ -2732,7 +2732,7 @@ A slightly different variant of the problem is placing pointers in a container t * Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals. * Static analysis can catch many 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 +### F.43: Never (directly or indirectly) return a pointer to a local object ##### Reason @@ -2829,7 +2829,7 @@ It can be detected/prevented with similar techniques. Preventable through static analysis. -### F.44: Return a `T&` when "returning no object" isn't needed +### F.44: Return a `T&` when "returning no object" isn't needed ##### Reason @@ -2859,7 +2859,7 @@ The language guarantees that a `T&` refers to an object, so that testing for `nu ??? -### F.45: Don't return a `T&&` +### F.45: Don't return a `T&&` ##### Reason @@ -2895,7 +2895,7 @@ Better: Flag any use of `&&` as a return type, except in `std::move` and `std::forward`. -### F.46: `int` is the return type for `main()` +### F.46: `int` is the return type for `main()` ##### Reason @@ -2949,7 +2949,7 @@ is not common enough to warrant violating consistency with standard types. This should be enforced by tooling by checking the return type (and return value) of any assignment operator. -### F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function) +### F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function) ##### Reason @@ -2982,7 +2982,7 @@ Functions can't capture local variables or be declared at local scope; if you ne * 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 +### F.51: Prefer overloading over default arguments for virtual functions ??? possibly other situations? @@ -3012,7 +3012,7 @@ Virtual function overrides do not inherit default arguments, leading to surprise 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 +### F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms ##### Reason @@ -3034,7 +3034,7 @@ This is a simple three-stage parallel pipeline. Each `stage` object encapsulates ??? -### F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread +### 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 @@ -3053,7 +3053,7 @@ Pointers and references to locals shouldn't outlive their scope. Lambdas that ca ??? -# C: Classes and Class Hierarchies +# C: Classes and Class Hierarchies A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces. Class hierarchies are used to organize related classes into hierarchical structures. @@ -3078,7 +3078,7 @@ 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) +### C.1: Organize related data into structures (`struct`s or `class`es) ##### Reason @@ -3101,7 +3101,7 @@ From a language perspective `class` and `struct` differ only in the default visi 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 +### C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently ##### Reason @@ -3134,7 +3134,7 @@ but: 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 +### C.3: Represent the distinction between an interface and an implementation using a class ##### Reason @@ -3166,7 +3166,7 @@ Ideally, and typically, an interface is far more stable than its implementation( ??? -### C.4: Make a function a member only if it needs direct access to the representation of a class +### C.4: Make a function a member only if it needs direct access to the representation of a class ##### Reason @@ -3193,7 +3193,7 @@ This rule becomes even better if C++17 gets "uniform function call." ??? 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 +### C.5: Place helper functions in the same namespace as the class they support ##### Reason @@ -3217,7 +3217,7 @@ Placing them in the same namespace as the class makes their relationship to the * 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` +### C.6: Declare a member function that does not modify the state of its object `const` ##### Reason @@ -3236,7 +3236,7 @@ More precise statement of design intent, better readability, more errors caught Flag non-`const` member functions that do not write to their objects -### C.7: Don't define a class or enum and declare a variable of its type in the same statement +### C.7: Don't define a class or enum and declare a variable of its type in the same statement ##### Reason @@ -3256,7 +3256,7 @@ Mixing a type definition and the definition of another entity in the same declar * Flag if the `}` of a class or enumeration definition is not followed by a `;`. The `;` is missing. -## C.concrete: Concrete types +## C.concrete: Concrete types One ideal for a class is to be a regular type. That means roughly "behaves like an `int`." A concrete type is the simplest kind of class. @@ -3271,7 +3271,7 @@ Concrete type rule summary: * [C.10: Prefer a concrete type over more complicated classes](#Rc-concrete) * [C.11: Make concrete types regular](#Rc-regular) -### C.10 Prefer a concrete type over more complicated classes +### C.10 Prefer a concrete type over more complicated classes ##### Reason @@ -3321,7 +3321,7 @@ This is done where dynamic allocation is prohibited (e.g. hard real-time) and to ??? -### C.11: Make concrete types regular +### C.11: Make concrete types regular ##### Reason @@ -3348,7 +3348,7 @@ In particular, if a concrete type has an assignment also give it an equals opera ??? -## C.ctor: Constructors, assignments, and destructors +## C.ctor: Constructors, assignments, and destructors These functions control the lifecycle of objects: creation, copy, move, and destruction. Define constructors to guarantee and simplify initialization of classes. @@ -3424,12 +3424,12 @@ Other default operations rules: * [C.88: Make `<` symmetric with respect of operand types and `noexcept`](#Rc-lt) * [C.89: Make a `hash` `noexcept`](#Rc-hash) -## C.defop: Default Operations +## C.defop: Default Operations By default, the language supply the default operations with their default semantics. However, a programmer can disable or replace these defaults. -### C.20: If you can avoid defining default operations, do +### C.20: If you can avoid defining default operations, do ##### Reason @@ -3459,7 +3459,7 @@ This is known as "the rule of zero". (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 +### C.21: If you define or `=delete` any default operation, define or `=delete` them all ##### Reason @@ -3508,7 +3508,7 @@ Relying on an implicitly generated copy operation in a class with a destructor i (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 +### C.22: Make default operations consistent ##### Reason @@ -3537,14 +3537,14 @@ These operations disagree about copy semantics. This will lead to confusion and * (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 +## C.dtor: Destructors "Does this class need a destructor?" is a surprisingly powerful design question. For most classes the answer is "no" either because the class holds no resources or because destruction is handled by [the rule of zero](#Rc-zero); 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 +### C.30: Define a destructor if a class needs an explicit action at object destruction ##### Reason @@ -3606,7 +3606,7 @@ If the default destructor is needed, but its generation has been suppressed (e.g 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 +### C.31: All resources acquired by a class must be released by the class's destructor ##### Reason @@ -3663,7 +3663,7 @@ Here `p` refers to `pp` but does not own it. * (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership (e.g., look into the constructors). -### C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning +### C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning ##### Reason @@ -3682,7 +3682,7 @@ This will aide documentation and analysis. 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 +### C.33: If a class has an owning pointer member, define a destructor ##### Reason @@ -3754,7 +3754,7 @@ That would sometimes require non-trivial code changes and may affect ABIs. * 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 +### C.34: If a class has an owning reference member, define a destructor ##### Reason @@ -3810,7 +3810,7 @@ Also, that may affect ABIs. * 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 destructor should be either public and virtual, or protected and nonvirtual +### C.35: A base class destructor should be either public and virtual, or protected and nonvirtual ##### Reason @@ -3870,7 +3870,7 @@ We can imagine one case where you could want a protected virtual destructor: Whe * A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual. -### C.36: A destructor may not fail +### C.36: A destructor may not fail ##### Reason @@ -3924,7 +3924,7 @@ If a destructor uses operations that may fail, it can catch exceptions and in so (Simple) A destructor should be declared `noexcept`. -### C.37: Make destructors `noexcept` +### C.37: Make destructors `noexcept` ##### Reason @@ -3938,11 +3938,11 @@ A destructor (either user-defined or compiler-generated) is implicitly declared (Simple) A destructor should be declared `noexcept`. -## C.ctor: Constructors +## C.ctor: Constructors A constructor defines how an object is initialized (constructed). -### C.40: Define a constructor if a class has an invariant +### C.40: Define a constructor if a class has an invariant ##### Reason @@ -4000,7 +4000,7 @@ Also, the default for `int` would be better done as a [member initializer](#Rc-i * Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant) -### C.41: A constructor should create a fully initialized object +### C.41: A constructor should create a fully initialized object ##### Reason @@ -4036,7 +4036,7 @@ Compilers do not read comments. 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 Acquisition Is Initialization"). -### C.42: If a constructor cannot construct a valid object, throw an exception +### C.42: If a constructor cannot construct a valid object, throw an exception ##### Reason @@ -4122,7 +4122,7 @@ Another reason is been to delay initialization until an object is needed; the so * (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: Ensure that a class has a default constructor +### C.43: Ensure that a class has a default constructor ##### Reason @@ -4202,7 +4202,7 @@ Assuming that you want initialization, an explicit default initialization can he * Flag classes without a default constructor -### C.44: Prefer default constructors to be simple and non-throwing +### C.44: Prefer default constructors to be simple and non-throwing ##### Reason @@ -4247,7 +4247,7 @@ Setting a `Vector1` to empty after detecting an error is trivial. * Flag throwing default constructors -### C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead +### C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead ##### Reason @@ -4277,7 +4277,7 @@ Using in-class member initializers lets the compiler generate the function for y (Simple) A default constructor should do more than just initialize member variables with constants. -### C.46: By default, declare single-argument constructors explicit +### C.46: By default, declare single-argument constructors explicit ##### Reason @@ -4313,7 +4313,7 @@ If you really want an implicit conversion from the constructor argument type to (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 +### C.47: Define and initialize member variables in the order of member declaration ##### Reason @@ -4337,7 +4337,7 @@ To minimize confusion and errors. That is the order in which the initialization **See also**: [Discussion](#Sd-order) -### C.48: Prefer in-class initializers to member initializers in constructors for constant initializers +### C.48: Prefer in-class initializers to member initializers in constructors for constant initializers ##### Reason @@ -4386,7 +4386,7 @@ How would a maintainer know whether `j` was deliberately uninitialized (probably * (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 +### C.49: Prefer initialization to assignment in constructors ##### Reason @@ -4417,7 +4417,7 @@ An initialization explicitly states that initialization, rather than assignment, // ... }; -### C.50: Use a factory function if you need "virtual behavior" during initialization +### C.50: Use a factory function if you need "virtual behavior" during initialization ##### Reason @@ -4477,7 +4477,7 @@ Conventional factory functions allocate on the free store, rather than on the st **See also**: [Discussion](#Sd-factory) -### C.51: Use delegating constructors to represent common actions for all constructors of a class +### C.51: Use delegating constructors to represent common actions for all constructors of a class ##### Reason @@ -4524,7 +4524,7 @@ The common action gets tedious to write and may accidentally not be common. (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 +### C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization ##### Reason @@ -4558,13 +4558,13 @@ If you need those constructors for a derived class, re-implementing them is tedi Make sure that every member of the derived class is initialized. -## C.copy: Copy and move +## C.copy: Copy and move Value types should generally be copyable, but interfaces in a class hierarchy should not. 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&` +### C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&` ##### Reason @@ -4633,7 +4633,7 @@ See [copy constructor vs. `clone()`](#Rc-copy-virtual). * (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators. Look at the destructor to determine if the type has pointer semantics or value semantics. -### C.61: A copy operation should copy +### C.61: A copy operation should copy ##### Reason @@ -4704,7 +4704,7 @@ Prefer copy semantics unless you are building a "smart pointer". Value semantics (Not enforceable) -### C.62: Make copy assignment safe for self-assignment +### C.62: Make copy assignment safe for self-assignment ##### Reason @@ -4770,7 +4770,7 @@ Consider: (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 &` +### C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const &` ##### Reason @@ -4786,7 +4786,7 @@ Equivalent to what is done for [copy-assignment](#Rc-copy-assignment). * (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 +### C.64: A move operation should move and leave its source in valid state ##### Reason @@ -4836,7 +4836,7 @@ Unless there is an exceptionally strong reason not to, make `x = std::move(y); y (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 +### C.65: Make move assignment safe for self-assignment ##### Reason @@ -4885,7 +4885,7 @@ Here is a way to move a pointer without a test (imagine it as code in the implem * (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` +### C.66: Make move operations `noexcept` ##### Reason @@ -4926,7 +4926,7 @@ This `Vector2` is not just inefficient, but since a vector copy requires allocat (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 +### C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired ##### Reason @@ -4981,7 +4981,7 @@ A class with any virtual function should not have a copy constructor or copy ass ??? -### C.80: Use `=default` if you have to be explicit about using the default semantics +### C.80: Use `=default` if you have to be explicit about using the default semantics ##### Reason @@ -5023,7 +5023,7 @@ Writing out the bodies of the copy and move operations is verbose, tedious, and (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) +### C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative) ##### Reason @@ -5073,7 +5073,7 @@ A `unique_ptr` can be moved, but not copied. To achieve that its copy operations 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 +### C.82: Don't call virtual functions in constructors and destructors ##### Reason @@ -5110,7 +5110,7 @@ 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 +### C.83: For value-like types, consider providing a `noexcept` swap function ##### Reason @@ -5143,7 +5143,7 @@ Providing a nonmember `swap` function in the same namespace as your type for cal * (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 +### C.84: A `swap` function may not fail ##### Reason @@ -5164,7 +5164,7 @@ This is not just slow, but if a memory allocation occurs for the elements in `tm (Simple) When a class has a `swap` member function, it should be declared `noexcept`. -### C.85: Make `swap` `noexcept` +### C.85: Make `swap` `noexcept` ##### Reason @@ -5175,7 +5175,7 @@ If a `swap` tries to exit with an exception, it's a bad design error and the pro (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` +### C.86: Make `==` symmetric with respect to operand types and `noexcept` ##### Reason @@ -5211,7 +5211,7 @@ The alternative is to make two failure states compare equal and any valid state ??? -### C.87: Beware of `==` on base classes +### C.87: Beware of `==` on base classes ##### Reason @@ -5255,7 +5255,7 @@ Of course there are ways of making `==` work in a hierarchy, but the naive appro ??? -### C.88: Make `<` symmetric with respect to operand types and `noexcept` +### C.88: Make `<` symmetric with respect to operand types and `noexcept` ##### Reason @@ -5269,7 +5269,7 @@ Of course there are ways of making `==` work in a hierarchy, but the naive appro ??? -### C.89: Make a `hash` `noexcept` +### C.89: Make a `hash` `noexcept` ##### Reason @@ -5283,7 +5283,7 @@ Of course there are ways of making `==` work in a hierarchy, but the naive appro ??? -## C.con: Containers and other resource handles +## C.con: Containers and other resource handles A container is an object holding a sequence of objects of some type; `std::vector` is the archetypical container. A resource handle is a class that owns a resource; `std::vector` is the typical resource handle; its resource is its sequence of elements. @@ -5301,7 +5301,7 @@ Summary of container rules: **See also**: [Resources](#S-resource) -## C.lambdas: Function objects and lambdas +## C.lambdas: Function objects and lambdas A function object is an object supplying an overloaded `()` so that you can call it. A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object. @@ -5314,7 +5314,7 @@ 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) +## C.hier: Class hierarchies (OOP) A class hierarchy is constructed to represent a set of hierarchically organized concepts (only). Typically base classes act as interfaces. @@ -5355,7 +5355,7 @@ 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) +### C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only) ##### Reason @@ -5400,7 +5400,7 @@ not using this (over)general interface in favor of a particular interface found * Look for classes with lots of members that do nothing but throw. * Flag every use of a nonpublic base class `B` where the derived class `D` does not override a virtual function or access a protected member in `B`, and `B` is not one of the following: empty, a template parameter or parameter pack of `D`, a class template specialized with `D`. -### C.121: If a base class is used as an interface, make it a pure abstract class +### C.121: If a base class is used as an interface, make it a pure abstract class ##### Reason @@ -5418,7 +5418,7 @@ A class is more stable (less brittle) if it does not contain data. Interfaces sh * 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 +### C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed ##### Reason @@ -5434,7 +5434,7 @@ Such as on an ABI (link) boundary. ## C.hierclass: Designing classes in a hierarchy: -### C.126: An abstract class typically doesn't need a constructor +### C.126: An abstract class typically doesn't need a constructor ##### Reason @@ -5454,7 +5454,7 @@ An abstract class typically does not have any data for a constructor to initiali Flag abstract classes with constructors. -### C.127: A class with a virtual function should have a virtual destructor +### C.127: A class with a virtual function should have a virtual destructor ##### Reason @@ -5485,7 +5485,7 @@ There are people who don't follow this rule because they plan to use a class onl * 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: Virtual functions should specify exactly one of `virtual`, `override`, or `final` +### C.128: Virtual functions should specify exactly one of `virtual`, `override`, or `final` ##### Reason @@ -5520,7 +5520,7 @@ Use `virtual` only when declaring a new virtual function. Use `override` only wh * Flag function declarations that use more than one of `virtual`, `override`, and `final`. -### C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance +### C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance ##### Reason @@ -5534,7 +5534,7 @@ Use `virtual` only when declaring a new virtual function. Use `override` only wh ??? -### C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead +### C.130: Redefine or prohibit copying for a base class; prefer a virtual `clone` function instead ##### Reason @@ -5565,7 +5565,7 @@ Note that because of language rules, the covariant return type cannot be a smart * Flag an assignment of base class objects (objects of a class from which another has been derived). -### C.131: Avoid trivial getters and setters +### C.131: Avoid trivial getters and setters ##### Reason @@ -5600,7 +5600,7 @@ A getter or a setter that converts from an internal type to an interface type is 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 +### C.132: Don't make a function `virtual` without reason ##### Reason @@ -5627,7 +5627,7 @@ This kind of "vector" isn't meant to be used as a base class at all. * 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 +### C.133: Avoid `protected` data ##### Reason @@ -5647,7 +5647,7 @@ Protected member function can be just fine. Flag classes with `protected` data. -### C.134: Ensure all non-`const` data members have the same access level +### C.134: Ensure all non-`const` data members have the same access level ##### Reason @@ -5683,7 +5683,7 @@ Occasionally classes will mix A and B, usually for debug reasons. An encapsulate Flag any class that has non-`const` data members with different access levels. -### C.135: Use multiple inheritance to represent multiple distinct interfaces +### C.135: Use multiple inheritance to represent multiple distinct interfaces ##### Reason @@ -5706,7 +5706,7 @@ Such interfaces are typically abstract classes. ??? -### C.136: Use multiple inheritance to represent the union of implementation attributes +### C.136: Use multiple inheritance to represent the union of implementation attributes ##### Reason @@ -5724,7 +5724,7 @@ This a relatively rare use because implementation can often be organized into a ??? 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 +### C.137: Use `virtual` bases to avoid overly general base classes ##### Reason @@ -5742,7 +5742,7 @@ This a relatively rare use because implementation can often be organized into a ??? -### C.138: Create an overload set for a derived class and its bases with `using` +### C.138: Create an overload set for a derived class and its bases with `using` ##### Reason @@ -5753,7 +5753,7 @@ This a relatively rare use because implementation can often be organized into a ??? -### C.139: Use `final` sparingly +### C.139: Use `final` sparingly ##### Reason @@ -5816,7 +5816,7 @@ Flag uses of `final`. ## C.hier-access: Accessing objects in a hierarchy -### C.145: Access polymorphic objects through pointers and references +### C.145: Access polymorphic objects through pointers and references ##### Reason @@ -5856,7 +5856,7 @@ You can safely access a named polymorphic object in the scope of its definition, Flag all slicing. -### C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable +### C.146: Use `dynamic_cast` where class hierarchy navigation is unavoidable ##### Reason @@ -5954,7 +5954,7 @@ In very rare cases, if you have measured that the `dynamic_cast` overhead is mat 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 +### C.147: Use `dynamic_cast` to a reference type when failure to find the required class is considered an error ##### Reason @@ -5968,7 +5968,7 @@ Casting to a reference expresses that you intend to end up with a valid object, ??? -### C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative +### C.148: Use `dynamic_cast` to a pointer type when failure to find the required class is considered a valid alternative ##### Reason @@ -5982,7 +5982,7 @@ Casting to a reference expresses that you intend to end up with a valid object, ??? -### C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new` +### C.149: Use `unique_ptr` or `shared_ptr` to avoid forgetting to `delete` objects created using `new` ##### Reason @@ -6003,7 +6003,7 @@ Avoid resource leaks. * 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 +### C.150: Use `make_unique()` to construct objects owned by `unique_ptr`s ##### Reason @@ -6034,7 +6034,7 @@ It also ensures exception safety in complex expressions. * 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 +### C.151: Use `make_shared()` to construct objects owned by `shared_ptr`s ##### Reason @@ -6052,7 +6052,7 @@ It also gives an opportunity to eliminate a separate allocation for the referenc * 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 +### C.152: Never assign a pointer to an array of derived class objects to a pointer to its base ##### Reason @@ -6076,7 +6076,7 @@ Subscripting the resulting base pointer will lead to invalid object access and p * Flag all combinations of array decay and base to derived conversions. * Pass an array as a `span` rather than as a pointer, and don't let the array name suffer a derived-to-base conversion before getting into the `span` -## C.over: Overloading and overloaded operators +## C.over: Overloading and overloaded operators You can overload ordinary functions, template functions, and operators. You cannot overload function objects. @@ -6093,7 +6093,7 @@ Overload rule summary: * [C.167: Use an operator for an operation with its conventional meaning](#Ro-overload) * [C.170: If you feel like overloading a lambda, use a generic lambda](#Ro-lambda) -### C.160: Define operators primarily to mimic conventional usage +### C.160: Define operators primarily to mimic conventional usage ##### Reason @@ -6109,7 +6109,7 @@ Minimize surprises. Possibly impossible. -### C.161: Use nonmember functions for symmetric operators +### C.161: Use nonmember functions for symmetric operators ##### Reason @@ -6124,7 +6124,7 @@ Unless you use a non-member function for (say) `==`, `a == b` and `b == a` will Flag member operator functions. -### C.162: Overload operations that are roughly equivalent +### C.162: Overload operations that are roughly equivalent ##### Reason @@ -6150,7 +6150,7 @@ These three functions all print their arguments (appropriately). Adding to the n ??? -### C.163: Overload only for operations that are roughly equivalent +### C.163: Overload only for operations that are roughly equivalent ##### Reason @@ -6179,7 +6179,7 @@ Be particularly careful about common and popular names, such as `open`, `move`, ??? -### C.164: Avoid conversion operators +### C.164: Avoid conversion operators ##### Reason @@ -6220,7 +6220,7 @@ Flag all conversion operators. -### C.165: Use `using` for customization points +### C.165: Use `using` for customization points ##### Reason @@ -6267,7 +6267,7 @@ This is done by including the general function in the lookup for the function: Unlikely, except for known customization points, such as `swap`. The problem is that the unqualified and qualified lookups both have uses. -### C.166: Overload unary `&` only as part of a system of smart pointers and references +### C.166: Overload unary `&` only as part of a system of smart pointers and references ##### Reason @@ -6303,7 +6303,7 @@ Tricky. Warn if `&` is user-defined without also defining `->` for the result ty -### C.167: Use an operator for an operation with its conventional meaning +### C.167: Use an operator for an operation with its conventional meaning ##### Reason @@ -6342,7 +6342,7 @@ Don't define those unconventionally and don't invent yur own names for them. Tricky. Requires semantic insight. -### C.170: If you feel like overloading a lambda, use a generic lambda +### C.170: If you feel like overloading a lambda, use a generic lambda ##### Reason @@ -6363,7 +6363,7 @@ You can overload by defining two different lambdas with the same name. The compiler catches the attempt to overload a lambda. -## C.union: Unions +## C.union: Unions ??? @@ -6374,7 +6374,7 @@ Union rule summary: * [C.182: Use anonymous `union`s to implement tagged unions](#Ru-anonymous) * ??? -### C.180: Use `union`s to ??? +### 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 @@ -6391,7 +6391,7 @@ Union rule summary: ??? -### C.181: Avoid "naked" `union`s +### C.181: Avoid "naked" `union`s ##### Reason @@ -6409,7 +6409,7 @@ Naked unions are a source of type errors. ??? -### C.182: Use anonymous `union`s to implement tagged unions +### C.182: Use anonymous `union`s to implement tagged unions ##### Reason @@ -6423,7 +6423,7 @@ Naked unions are a source of type errors. ??? -# Enum: Enumerations +# Enum: Enumerations Enumerations are used to define sets of integer values and for defining types for such sets of values. There are two kind of enumerations, "plain" `enum`s and `class enum`s. @@ -6437,7 +6437,7 @@ Enumeration rule summary: * [Enum.6: Use unnamed enumerations for ???](#Renum-unnamed) * ??? -### Enum.1: Prefer enums over macros +### Enum.1: Prefer enums over macros ##### Reason @@ -6472,7 +6472,7 @@ Instead use an `enum`: Flag macros that define integer values -### Enum.2: Use enumerations to represent sets of named constants +### Enum.2: Use enumerations to represent sets of named constants ##### Reason @@ -6486,7 +6486,7 @@ An enumeration shows the enumerators to be related and can be a named type ??? -### Enum.3: Prefer class enums over "plain" enums +### Enum.3: Prefer class enums over "plain" enums ##### Reason @@ -6520,7 +6520,7 @@ Instead use an `enum class`: (Simple) Warn on any non-class enum definition. -### Enum.4: Define operations on enumerations for safe and simple use +### Enum.4: Define operations on enumerations for safe and simple use ##### Reason @@ -6534,7 +6534,7 @@ Convenience of use and avoidance of errors. ??? -### Enum.5: Don't use `ALL_CAPS` for enumerators +### Enum.5: Don't use `ALL_CAPS` for enumerators ##### Reason @@ -6548,7 +6548,7 @@ Avoid clashes with macros. ??? -### Enum.6: Use unnamed enumerations for ??? +### Enum.6: Use unnamed enumerations for ??? ##### Reason @@ -6562,7 +6562,7 @@ Avoid clashes with macros. ??? -# R: Resource management +# R: Resource management This section contains rules related to resources. A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks. @@ -6593,7 +6593,7 @@ Here, we ignore such cases. * [R.14: ??? array vs. pointer parameter](#Rr-ap) * [R.15: Always overload matched allocation/deallocation pairs](#Rr-pair) -* Smart pointer rule summary: +* Smart pointer rule summary: * [R.20: Use `unique_ptr` or `shared_ptr` to represent ownership](#Rr-owner) * [R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership](#Rr-unique) @@ -6609,7 +6609,7 @@ Here, we ignore such cases. * [R.36: Take a `const shared_ptr&` parameter to express that it might retain a reference count to the object ???](#Rr-sharedptrparam-const) * [R.37: Do not pass a pointer or reference obtained from an aliased smart pointer](#Rr-smartptrget) -### R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization) +### R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization) ##### Reason @@ -6671,7 +6671,7 @@ Where a resource is "ill-behaved" in that it isn't represented as a class with a **See also**: [RAII](#Rr-raii). -### R.2: In interfaces, use raw pointers to denote individual objects (only) +### R.2: In interfaces, use raw pointers to denote individual objects (only) ##### Reason @@ -6711,7 +6711,7 @@ However, where `nullptr` is a possible value, a reference may not be an reasonab 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 +### R.3: A raw pointer (a `T*`) is non-owning ##### Reason @@ -6805,7 +6805,7 @@ If pointer semantics are required (e.g., because the return type needs to refer * (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor. Suggest considering returning it by value instead. -### R.4: A raw reference (a `T&`) is non-owning +### R.4: A raw reference (a `T&`) is non-owning ##### Reason @@ -6827,7 +6827,7 @@ We want owners identified so that we can reliably and efficiently delete the obj See [the raw pointer rule](#Rr-ptr) -### R.5: Don't heap-allocate unnecessarily +### R.5: Don't heap-allocate unnecessarily ##### Reason @@ -6859,7 +6859,7 @@ Instead, use a local variable: * (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 +### R.6: Avoid non-`const` global variables ##### Reason @@ -6878,9 +6878,9 @@ Note that it is possible to get undefined initialization order even for `const` (??? NM: Obviously we can warn about non-`const` statics ... do we want to?) -## R.alloc: Allocation and deallocation +## R.alloc: Allocation and deallocation -### R.10: Avoid `malloc()` and `free()` +### R.10: Avoid `malloc()` and `free()` ##### Reason @@ -6926,7 +6926,7 @@ In such cases, consider the `nothrow` versions of `new`. Flag explicit use of `malloc` and `free`. -### R.11: Avoid calling `new` and `delete` explicitly +### R.11: Avoid calling `new` and `delete` explicitly ##### Reason @@ -6944,7 +6944,7 @@ If you have a naked `new`, you probably need a naked `delete` somewhere, so you (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 +### R.12: Immediately give the result of an explicit resource allocation to a manager object ##### Reason @@ -6977,7 +6977,7 @@ The use of the file handle (in `ifstream`) is simple, efficient, and safe. * 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 +### R.13: Perform at most one explicit resource allocation in a single expression statement ##### Reason @@ -7012,7 +7012,7 @@ Write your own factory wrapper if there is not one already. * Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?) -### R.14: ??? array vs. pointer parameter +### R.14: ??? array vs. pointer parameter ##### Reason @@ -7028,7 +7028,7 @@ An array decays to a pointer, thereby losing its size, opening the opportunity f Flag `[]` parameters. -### R.15: Always overload matched allocation/deallocation pairs +### R.15: Always overload matched allocation/deallocation pairs ##### Reason @@ -7052,9 +7052,9 @@ Don't leave it undeclared. Flag incomplete pairs. -## R.smart: Smart pointers +## R.smart: Smart pointers -### R.20: Use `unique_ptr` or `shared_ptr` to represent ownership +### R.20: Use `unique_ptr` or `shared_ptr` to represent ownership ##### Reason @@ -7078,7 +7078,7 @@ This will leak the object used to initialize `p1` (only). (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer. -### R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership +### R.21: Prefer `unique_ptr` over `shared_ptr` unless you need to share ownership ##### Reason @@ -7108,7 +7108,7 @@ This is more efficient: (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 +### R.22: Use `make_shared()` to make `shared_ptr`s ##### Reason @@ -7127,7 +7127,7 @@ The `make_shared()` version mentions `X` only once, so it is usually shorter (as (Simple) Warn if a `shared_ptr` is constructed from the result of `new` rather than `make_shared`. -### R.23: Use `make_unique()` to make `unique_ptr`s +### R.23: Use `make_unique()` to make `unique_ptr`s ##### Reason @@ -7141,7 +7141,7 @@ For convenience and consistency with `shared_ptr`. (Simple) Warn if a `unique_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 +### R.24: Use `std::weak_ptr` to break cycles of `shared_ptr`s ##### Reason @@ -7162,7 +7162,7 @@ You could "temporarily share ownership" simply by using another `stared_ptr`.) ??? 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 +### R.30: Take smart pointers as parameters only to explicitly express lifetime semantics ##### Reason @@ -7209,7 +7209,7 @@ A function that does not manipulate lifetime should take raw pointers or referen * (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` +### R.31: If you have non-`std` smart pointers, follow the basic pattern from `std` ##### Reason @@ -7242,7 +7242,7 @@ Both cases are an error under the [`sharedptrparam` guideline](#Rr-smartptrparam these functions should accept a smart pointer only if they need to participate in the widget's lifetime management. Otherwise they should accept a `widget*`, if it can be `nullptr`. Otherwise, and ideally, the function should accept a `widget&`. These smart pointers match the `Shared_ptr` concept, so these guideline enforcement rules work on them out of the box and expose this common pessimization. -### R.32: Take a `unique_ptr` parameter to express that a function assumes ownership of a `widget` +### R.32: Take a `unique_ptr` parameter to express that a function assumes ownership of a `widget` ##### Reason @@ -7264,7 +7264,7 @@ Using `unique_ptr` in this way both documents and enforces the function call's o * (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` +### R.33: Take a `unique_ptr&` parameter to express that a function reseats the`widget` ##### Reason @@ -7288,7 +7288,7 @@ Using `unique_ptr` in this way both documents and enforces the function call's r * (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 +### R.34: Take a `shared_ptr` parameter to express that a function is part owner ##### Reason @@ -7308,7 +7308,7 @@ This makes the function's ownership sharing explicit. * (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 +### R.35: Take a `shared_ptr&` parameter to express that a function might reseat the shared pointer ##### Reason @@ -7332,7 +7332,7 @@ This makes the function's reseating explicit. * (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 ??? +### R.36: Take a `const shared_ptr&` parameter to express that it might retain a reference count to the object ??? ##### Reason @@ -7352,7 +7352,7 @@ This makes the function's ??? explicit. * (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 +### R.37: Do not pass a pointer or reference obtained from an aliased smart pointer ##### Reason @@ -7405,7 +7405,7 @@ The fix is simple -- take a local copy of the pointer to "keep a ref count" for * (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 +# 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. @@ -7483,7 +7483,7 @@ Arithmetic rules: * [ES.104: Don't underflow](#Res-underflow) * [ES.105: Don't divide by zero](#Res-zero) -### ES.1: Prefer the standard library to other libraries and to "handcrafted code" +### ES.1: Prefer the standard library to other libraries and to "handcrafted code" ##### Reason @@ -7512,7 +7512,7 @@ but don't hand-code a well-known algorithm: 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 +### ES.2: Prefer suitable abstractions to direct use of language features ##### Reason @@ -7553,7 +7553,7 @@ Not easy. ??? Look for messy loops, nested loops, long functions, absence of fun 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 +### ES.5: Keep scopes small ##### Reason @@ -7615,7 +7615,7 @@ I am assuming that `Record` is large and doesn't have a good move operation so t * 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 +### ES.6: Declare names in for-statement initializers and conditions to limit scope ##### Reason @@ -7645,7 +7645,7 @@ Readability. Minimize resource retention. * 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 +### ES.7: Keep common and local names short, and keep uncommon and nonlocal names longer ##### Reason @@ -7714,7 +7714,7 @@ We recommend keeping functions short, but that rule isn't universally adhered to Check length of local and non-local names. Also take function length into account. -### ES.8: Avoid similar-looking names +### ES.8: Avoid similar-looking names ##### Reason @@ -7741,7 +7741,7 @@ Antique header files might declare non-types and types with the same name in the * Flag a declaration of a variable, function, or enumerator that hides a class or enumeration declared in the same scope. -### ES.9: Avoid `ALL_CAPS` names +### ES.9: Avoid `ALL_CAPS` names ##### Reason @@ -7772,7 +7772,7 @@ Do not use `ALL_CAPS` for constants just because constants used to be macros. 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 +### ES.10: Declare one name (only) per declaration ##### Reason @@ -7812,7 +7812,7 @@ or: 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 +### ES.11: Use `auto` to avoid redundant repetition of type names ##### Reason @@ -7855,7 +7855,7 @@ When concepts become available, we can (and should) be more specific about the t Flag redundant repetition of type names in a declaration. -### ES.20: Always initialize an object +### ES.20: Always initialize an object ##### Reason @@ -8036,7 +8036,7 @@ or maybe: * Check that an uninitialized buffer is written into *immediately* after declaration. Passing a uninitialized variable as a reference to non-`const` argument can be assumed to be a write into the variable. -### ES.21: Don't introduce a variable (or constant) before you need to use it +### ES.21: Don't introduce a variable (or constant) before you need to use it ##### Reason @@ -8052,7 +8052,7 @@ Readability. To limit the scope in which the variable can be used. Flag declaration that distant from their first use. -### ES.22: Don't declare a variable until you have a value to initialize it with +### ES.22: Don't declare a variable until you have a value to initialize it with ##### Reason @@ -8092,7 +8092,7 @@ For initializers of moderate complexity, including for `const` variables, consid * 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 +### ES.23: Prefer the `{}` initializer syntax ##### Reason @@ -8171,7 +8171,7 @@ 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 +### ES.24: Use a `unique_ptr` to hold pointers in code that may throw ##### Reason @@ -8194,7 +8194,7 @@ If `leak == true` the object pointed to by `p2` is leaked and the object pointed 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 +### ES.25: Declare an objects `const` or `constexpr` unless you want to modify its value later on ##### Reason @@ -8213,7 +8213,7 @@ That way you can't change the value by mistake. That way may offer the compiler 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 +### ES.26: Don't use a variable for two unrelated purposes ##### Reason @@ -8232,7 +8232,7 @@ Readability. Flag recycled variables. -### ES.27: Use `std::array` or `stack_array` for arrays on the stack +### ES.27: Use `std::array` or `stack_array` for arrays on the stack ##### Reason @@ -8276,7 +8276,7 @@ The definition of `a2` is C but not C++ and is considered a security risk * 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 +### ES.28: Use lambdas for complex initialization, especially of `const` variables ##### Reason @@ -8325,7 +8325,7 @@ If at all possible, reduce the conditions to a simple set of alternatives (e.g., 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 +### ES.30: Don't use macros for program text manipulation ##### Reason @@ -8348,7 +8348,7 @@ This rule does not ban the use of macros for "configuration control" use in `#if 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" +### ES.31: Don't use macros for constants or "functions" ##### Reason @@ -8372,7 +8372,7 @@ Even if we hadn't left a well-known bug in `SQUARE` there are much better behave Scream when you see a macro that isn't just used for source control (e.g., `#ifdef`) -### ES.32: Use `ALL_CAPS` for all macro names +### ES.32: Use `ALL_CAPS` for all macro names ##### Reason @@ -8388,7 +8388,7 @@ Convention. Readability. Distinguishing macros. Scream when you see a lower case macro. -### ES.33: If you must use macros, give them unique names +### ES.33: If you must use macros, give them unique names ##### Reason @@ -8410,7 +8410,7 @@ If you are forced to use macros, use long names and supposedly unique prefixes ( Warn against short macro names. -### ES.40: Don't define a (C-style) variadic function +### ES.40: Don't define a (C-style) variadic function ##### Reason @@ -8434,7 +8434,7 @@ Flag definitions of C-style variadic functions. 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 +### ES.70: Prefer a `switch`-statement to an `if`-statement when there is a choice ##### Reason @@ -8466,7 +8466,7 @@ rather than: 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 +### ES.71: Prefer a range-`for`-statement to a `for`-statement when there is a choice ##### Reason @@ -8514,7 +8514,7 @@ This will copy each elements of `vs` into `s`. Better Look at loops, if a traditional loop just looks at each element of a sequence, and there are no side-effects on what it does with the elements, rewrite the loop to a for loop. -### ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable +### ES.72: Prefer a `for`-statement to a `while`-statement when there is an obvious loop variable ##### Reason @@ -8538,7 +8538,7 @@ Readability: the complete logic of the loop is visible "up front". The scope of ??? -### ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable +### ES.73: Prefer a `while`-statement to a `for`-statement when there is no obvious loop variable ##### Reason @@ -8552,7 +8552,7 @@ Readability: the complete logic of the loop is visible "up front". The scope of ??? -### ES.74: Prefer to declare a loop variable in the initializer part of as `for`-statement +### ES.74: Prefer to declare a loop variable in the initializer part of as `for`-statement ##### Reason @@ -8582,7 +8582,7 @@ Warn when a variable modified inside the `for`-statement is declared outside the **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 +### ES.75: Avoid `do`-statements ##### Reason @@ -8601,7 +8601,7 @@ The termination conditions is at the end (where it can be overlooked) and the co ??? -### ES.76: Avoid `goto` +### ES.76: Avoid `goto` ##### Reason @@ -8636,7 +8636,7 @@ This is an ad-hoc simulation of destructors. Declare your resources with handles * 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` +### ES.77: ??? `continue` ##### Reason @@ -8650,7 +8650,7 @@ This is an ad-hoc simulation of destructors. Declare your resources with handles ??? -### ES.78: Always end a non-empty `case` with a `break` +### ES.78: Always end a non-empty `case` with a `break` ##### Reason @@ -8704,7 +8704,7 @@ Multiple case labels of a single statement is OK: Flag all fall throughs from non-empty `case`s. -### ES.79: ??? `default` +### ES.79: ??? `default` ##### Reason @@ -8718,7 +8718,7 @@ Flag all fall throughs from non-empty `case`s. ??? -### ES.85: Make empty statements visible +### ES.85: Make empty statements visible ##### Reason @@ -8738,7 +8738,7 @@ Readability. Flag empty statements that are not blocks and doesn't "contain" comments. -### ES.86: Avoid modifying loop control variables inside the body of raw for-loops +### ES.86: Avoid modifying loop control variables inside the body of raw for-loops ##### Reason @@ -8766,7 +8766,7 @@ Flag variables that are potentially updated (have a non-const use) in both the l Expressions manipulate values. -### ES.40: Avoid complicated expressions +### ES.40: Avoid complicated expressions ##### Reason @@ -8821,7 +8821,7 @@ Tricky. How complicated must an expression be to be considered complicated? Writ * implementation defined behavior? * ??? -### ES.41: If in doubt about operator precedence, parenthesize +### ES.41: If in doubt about operator precedence, parenthesize ##### Reason @@ -8852,7 +8852,7 @@ You should know enough not to need parentheses for: * Flag assignment operators not as the leftmost operator. * ??? -### ES.42: Keep use of pointers simple and straightforward +### ES.42: Keep use of pointers simple and straightforward ##### Reason @@ -8870,7 +8870,7 @@ Complicated pointer manipulation is a major source of errors. We need a heuristic limiting the complexity of pointer arithmetic statement. -### ES.43: Avoid expressions with undefined order of evaluation +### ES.43: Avoid expressions with undefined order of evaluation ##### Reason @@ -8895,7 +8895,7 @@ What is safe? Can be detected by a good analyzer. -### ES.44: Don't depend on order of evaluation of function arguments +### ES.44: Don't depend on order of evaluation of function arguments ##### Reason @@ -8919,7 +8919,7 @@ The call will most likely be `f(0, 1)` or `f(1, 0)`, but you don't know which. T Can be detected by a good analyzer. -### ES.45: Avoid "magic constants"; use symbolic constants +### ES.45: Avoid "magic constants"; use symbolic constants ##### Reason @@ -8946,7 +8946,7 @@ Better still, don't expose constants: 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 +### ES.46: Avoid lossy (narrowing, truncating) arithmetic conversions ##### Reason @@ -8991,7 +8991,7 @@ A good analyzer can detect all narrowing conversions. However, flagging all narr * 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` +### ES.47: Use `nullptr` rather than `0` or `NULL` ##### Reason @@ -9010,7 +9010,7 @@ Consider: Flag uses of `0` and `NULL` for pointers. The transformation may be helped by simple program transformation. -### ES.48: Avoid casts +### ES.48: Avoid casts ##### Reason @@ -9043,7 +9043,7 @@ If you feel the need for a lot of casts, there may be a fundamental design probl * 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 +### ES.49: If you must use a cast, use a named cast ##### Reason @@ -9073,7 +9073,7 @@ The named casts are: Flag C-style and functional casts. -## ES.50: Don't cast away `const` +## ES.50: Don't cast away `const` ##### Reason @@ -9093,7 +9093,7 @@ Such examples are often handled as well or better using `mutable` or an indirect Flag `const_cast`s. -### ES.55: Avoid the need for range checking +### ES.55: Avoid the need for range checking ##### Reason @@ -9110,7 +9110,7 @@ Constructs that cannot overflow, don't, and usually runs faster: Look for explicit range checks and heuristically suggest alternatives. -### ES.60: Avoid `new` and `delete[]` outside resource management functions +### ES.60: Avoid `new` and `delete[]` outside resource management functions ##### Reason @@ -9137,7 +9137,7 @@ There can be code in the `...` part that causes the `delete` never to happen. Flag naked `new`s and naked `delete`s. -### ES.61: delete arrays using `delete[]` and non-arrays using `delete` +### ES.61: delete arrays using `delete[]` and non-arrays using `delete` ##### Reason @@ -9161,7 +9161,7 @@ This example not only violates the [no naked `new` rule](#Res-new) as in the pre * 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 +### ES.62: Don't compare pointers into different arrays ##### Reason @@ -9185,7 +9185,7 @@ This example has many more problems. ??? -### ES.63: Don't slice +### ES.63: Don't slice ##### Reason @@ -9224,9 +9224,9 @@ For example: Warn against slicing. -## Arithmetic +## Arithmetic -### ES.100: Don't mix signed and unsigned arithmetic +### ES.100: Don't mix signed and unsigned arithmetic ##### Reason @@ -9247,7 +9247,7 @@ This precludes consistency. Compilers already know and sometimes warn. -### ES.101: use unsigned types for bit manipulation +### ES.101: use unsigned types for bit manipulation ##### Reason @@ -9263,7 +9263,7 @@ Unsigned types support bit manipulation without surprises from sign bits. ??? -### ES.102: Used signed types for arithmetic +### ES.102: Used signed types for arithmetic ##### Reason @@ -9279,7 +9279,7 @@ Unsigned types support bit manipulation without surprises from sign bits. ??? -### ES.103: Don't overflow +### ES.103: Don't overflow ##### Reason @@ -9314,7 +9314,7 @@ Incrementing a value beyond a maximum value can lead to memory corruption and un ??? -### ES.104: Don't underflow +### ES.104: Don't underflow ##### Reason @@ -9335,7 +9335,7 @@ Decrementing a value beyond a minimum value can lead to memory corruption and un ??? -### ES.105: Don't divide by zero +### ES.105: Don't divide by zero ##### Reason @@ -9369,7 +9369,7 @@ This also applies to `%`. * Flag division by an integral value that could be zero -# PER: Performance +# PER: Performance ??? should this section be in the main guide??? @@ -9398,7 +9398,7 @@ 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 +### PER.1: Don't optimize without reason ##### Reason @@ -9410,7 +9410,7 @@ Some people optimize out of habit or because it's fun. ??? -### PER.2: Don't optimize prematurely +### PER.2: Don't optimize prematurely ##### Reason @@ -9418,7 +9418,7 @@ Elaborately optimized code is usually larger and harder to change than unoptimiz ??? -### PER.3: Don't optimize something that's not performance critical +### PER.3: Don't optimize something that's not performance critical ##### Reason @@ -9429,7 +9429,7 @@ Optimizing a non-performance-critical part of a program has no effect on system 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 +### PER.4: Don't assume that complicated code is necessarily faster than simple code ##### Reason @@ -9462,7 +9462,7 @@ Simple code can be very fast. Optimizers sometimes do marvels with simple code ??? -### PER.5: Don't assume that low-level code is necessarily faster than high-level code +### PER.5: Don't assume that low-level code is necessarily faster than high-level code ##### Reason @@ -9474,7 +9474,7 @@ Low-level code sometimes inhibits optimizations. Optimizers sometimes do marvels ??? -### PER.6: Don't make claims about performance without measurements +### PER.6: Don't make claims about performance without measurements ##### Reason @@ -9494,7 +9494,7 @@ Often, you will be surprised. ??? -### PER.10: Rely on the static type system +### PER.10: Rely on the static type system ##### Reason @@ -9502,27 +9502,27 @@ Type violations, weak types (e.g. `void*`s), and low level code (e.g., manipulat ??? -### PER.11: Move computation from run time to compile time +### PER.11: Move computation from run time to compile time ??? -### PER.12: Eliminate redundant aliases +### PER.12: Eliminate redundant aliases ??? -### PER.13: Eliminate redundant indirections +### PER.13: Eliminate redundant indirections ??? -### PER.14: Minimize the number of allocations and deallocations +### PER.14: Minimize the number of allocations and deallocations ??? -### PER.15: Do not allocate on a critical branch +### PER.15: Do not allocate on a critical branch ??? -### PER.16: Use compact data structures +### PER.16: Use compact data structures ##### Reason @@ -9530,11 +9530,11 @@ Performance is typically dominated by memory access times. ??? -### PER.17: Declare the most used member of a time critical struct first +### PER.17: Declare the most used member of a time critical struct first ??? -### PER.18: Space is time +### PER.18: Space is time ##### Reason @@ -9542,7 +9542,7 @@ Performance is typically dominated by memory access times. ??? -### PER.19: Access memory predictably +### PER.19: Access memory predictably ##### Reason @@ -9562,11 +9562,11 @@ Performance is very sensitive to cache performance and cache algorithms favor si for (int c = 0; c < cols; ++c) sum += matrix[r][c]; -### PER.30: Avoid context switches on the critical path +### PER.30: Avoid context switches on the critical path ??? -# CP: Concurrency and Parallelism +# CP: Concurrency and Parallelism ??? @@ -9582,7 +9582,7 @@ 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 +### CP.1: Assume that your code will run as part of a multi-threaded program ##### Reason @@ -9623,7 +9623,7 @@ was run as part of a multi-threaded program. Often years later. Typically, such programs lead to a painful effort to remove data races. Therefore, code that is never intended to run in a multi-threaded environment should be clearly labeled as such. -### CP.2: Avoid data races +### CP.2: Avoid data races ##### Reason @@ -9637,7 +9637,7 @@ In a nutshell, if two threads can access the same named object concurrently (wit Some is possible, do at least something. -## CP.con: Concurrency +## CP.con: Concurrency ??? @@ -9663,7 +9663,7 @@ It should definitely be mentioned that `volatile` does not provide atomicity, do ???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 +## CP.par: Parallelism ??? @@ -9672,7 +9672,7 @@ Parallelism rule summary: * ??? * ??? -## CP.simd: SIMD +## CP.simd: SIMD ??? @@ -9681,7 +9681,7 @@ SIMD rule summary: * ??? * ??? -## CP.free: Lock-free programming +## CP.free: Lock-free programming ??? @@ -9690,7 +9690,7 @@ Lock-free programming rule summary: * ??? * ??? -### Don't use lock-free programming unless you absolutely have to +### Don't use lock-free programming unless you absolutely have to ##### Reason @@ -9698,7 +9698,7 @@ It's error-prone and requires expert level knowledge of language features, machi **Alternative**: Use lock-free data structures implemented by others as part of some library. -# E: Error handling +# E: Error handling Error handling involves: @@ -9741,13 +9741,13 @@ 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 +### 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. -### E.2: Throw an exception to signal that a function can't perform its assigned task +### E.2: Throw an exception to signal that a function can't perform its assigned task ##### Reason @@ -9806,7 +9806,7 @@ Don't use a `throw` as simply an alternative way of returning a value from a fun **See also**: [discussion](#Sd-noexcept) -### E.3: Use exceptions for error handling only +### E.3: Use exceptions for error handling only ##### Reason @@ -9829,7 +9829,7 @@ 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 +### E.4: Design your error-handling strategy around invariants ##### Reason @@ -9839,7 +9839,7 @@ To use an objects it must be in a valid state (defined formally or informally by 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 +### E.5: Let a constructor establish an invariant, and throw if it cannot ##### Reason @@ -9856,7 +9856,7 @@ Not all member function can be called. ??? -### E.6: Use RAII to prevent leaks +### E.6: Use RAII to prevent leaks ##### Reason @@ -9960,7 +9960,7 @@ Prefer to use exceptions. ??? -### E.7: State your preconditions +### E.7: State your preconditions ##### Reason @@ -9968,7 +9968,7 @@ To avoid interface errors. **See also**: [precondition rule](#Ri-pre). -### E.8: State your postconditions +### E.8: State your postconditions ##### Reason @@ -9976,7 +9976,7 @@ 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 +### E.12: Use `noexcept` when exiting a function because of a `throw` is impossible or unacceptable ##### Reason @@ -10007,7 +10007,7 @@ 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 +### E.13: Never throw while being the direct owner of an object ##### Reason @@ -10035,7 +10035,7 @@ 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) +### E.14: Use purpose-designed user-defined types as exceptions (not built-in types) ##### Reason @@ -10114,7 +10114,7 @@ The standard-library classes derived from `exception` should be used only as bas 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 +### E.15: Catch exceptions from a hierarchy by reference ##### Reason @@ -10138,7 +10138,7 @@ Instead, use: 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 +### E.16: Destructors, deallocation, and `swap` must never fail ##### Reason @@ -10174,7 +10174,7 @@ Catch destructors, deallocation operations, and `swap`s that `throw`. Catch such **See also**: [discussion](#Sd-never-fail) -### E.17: Don't try to catch every exception in every function +### E.17: Don't try to catch every exception in every function ##### Reason @@ -10199,7 +10199,7 @@ Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii). * 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` +### E.18: Minimize the use of explicit `try`/`catch` ##### Reason @@ -10213,7 +10213,7 @@ Let cleanup actions on the unwinding path be handled by [RAII](#Re-raii). ??? -### E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available +### E.19: Use a `final_action` object to express cleanup if no suitable resource handle is available ##### Reason @@ -10230,14 +10230,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 +### E.25: ??? What to do in programs where exceptions cannot be thrown ##### Note ??? mostly, you can afford exceptions and code gets simpler with exceptions ??? **See also**: [Discussion](#Sd-???). -# Con: Constants and Immutability +# Con: Constants and Immutability You can't have a race condition on a constant. it is easier to reason about a program when many of the objects cannot change their values. @@ -10251,7 +10251,7 @@ 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 +### Con.1: By default, make objects immutable ##### Reason @@ -10267,7 +10267,7 @@ Immutable objects are easier to reason about, so make object non-`const` only wh ??? -### Con.2: By default, make member functions `const` +### Con.2: By default, make member functions `const` ##### Reason @@ -10291,7 +10291,7 @@ A member function should be marked `const` unless it changes the object's observ * Flag a member function that is not marked `const`, but that could be `const` because its definition does not modify any member variable. -### Con.3: By default, pass pointers and references to `const`s +### Con.3: By default, pass pointers and references to `const`s ##### Reason @@ -10305,7 +10305,7 @@ A member function should be marked `const` unless it changes the object's observ ??? -### Con.4: Use `const` to define objects with values that do not change after construction +### Con.4: Use `const` to define objects with values that do not change after construction ##### Reason @@ -10319,7 +10319,7 @@ A member function should be marked `const` unless it changes the object's observ ??? -### Con.5: Use `constexpr` for values that can be computed at compile time +### Con.5: Use `constexpr` for values that can be computed at compile time ##### Reason @@ -10333,7 +10333,7 @@ A member function should be marked `const` unless it changes the object's observ ??? -# T: Templates and generic programming +# T: Templates and generic programming Generic programming is programming using types and algorithms parameterized by types, values, and algorithms. In C++, generic programming is supported by the `template` language mechanisms. @@ -10431,11 +10431,11 @@ Other template rules summary: * [T.144: Don't specialize function templates](#Rt-specialize-function) * [T.??: ????](#Rt-???) -## T.gp: Generic programming +## T.gp: Generic programming Generic programming is programming using types and algorithms parameterized by types, values, and algorithms. -### T.1: Use templates to raise the level of abstraction of code +### T.1: Use templates to raise the level of abstraction of code ##### Reason @@ -10496,7 +10496,7 @@ is to efficiently generalize operations/algorithms over a set of types with simi * 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 +### T.2: Use templates to express algorithms that apply to many argument types ##### Reason @@ -10523,7 +10523,7 @@ Don't overabstract. ??? tough, probably needs a human -### T.3: Use templates to express containers and ranges +### T.3: Use templates to express containers and ranges ##### Reason @@ -10565,7 +10565,7 @@ See [Stable base](#Rt-abi). * Flag uses of `void*`s and casts outside low-level implementation code -### T.4: Use templates to express syntax tree manipulation +### T.4: Use templates to express syntax tree manipulation ##### Reason @@ -10577,7 +10577,7 @@ See [Stable base](#Rt-abi). **Exceptions**: ??? -### T.5: Combine generic and OO techniques to amplify their strengths, not their costs +### T.5: Combine generic and OO techniques to amplify their strengths, not their costs ##### Reason @@ -10609,7 +10609,7 @@ In a class template, nonvirtual functions are only instantiated if they're used * Flag a class template that declares new (non-inherited) virtual functions. -## T.concepts: Concept rules +## T.concepts: Concept rules Concepts is a facility for specifying requirements for template arguments. It is an [ISO technical specification](#Ref-conceptsTS), but not yet supported by currently shipping compilers. @@ -10635,9 +10635,9 @@ 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.con-use: Concept use -### T.10: Specify concepts for all template arguments +### T.10: Specify concepts for all template arguments ##### Reason @@ -10689,7 +10689,7 @@ This is typically only needed when (as part of template metaprogramming code) we Flag template type arguments without concepts -### T.11: Whenever possible use standard concepts +### T.11: Whenever possible use standard concepts ##### Reason @@ -10729,7 +10729,7 @@ 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 +### T.12: Prefer concept names over `auto` for local variables ##### Reason @@ -10745,7 +10745,7 @@ Hard. * ??? -### T.13: Prefer the shorthand notation for simple, single-type argument concepts +### T.13: Prefer the shorthand notation for simple, single-type argument concepts ##### Reason @@ -10771,11 +10771,11 @@ The shorter versions better match the way we speak. Note that many templates don * 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.concepts.def: Concept definition rules +## T.concepts.def: Concept definition rules ??? -### T.20: Avoid "concepts" without meaningful semantics +### T.20: Avoid "concepts" without meaningful semantics ##### Reason @@ -10841,7 +10841,7 @@ Concepts with multiple operations have far lower chance of accidentally matching * 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 +### T.21: Define concepts to define complete sets of operations ##### Reason @@ -10862,7 +10862,7 @@ Examples of complete sets are ??? -### T.22: Specify axioms for concepts +### T.22: Specify axioms for concepts ##### Reason @@ -10914,7 +10914,7 @@ However, it should not be assumed to be stable. Each new use case may require su * 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. +### T.23: Differentiate a refined concept from its more general case by adding new use patterns. ##### Reason @@ -10938,7 +10938,7 @@ they do not need any special declarations to "hook into the concept". * 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. +### T.24: Use tag classes or traits to differentiate concepts that differ only in semantics. ##### Reason @@ -10966,7 +10966,7 @@ Prefer the standard-library ones. * The compiler flags ambiguous use of identical concepts. * Flag the definition of identical concepts. -### T.25: Avoid negating constraints. +### T.25: Avoid negating constraints. ##### Reason @@ -11008,7 +11008,7 @@ The compiler will select the overload and emit an appropriate error. * Flag pairs of functions with `C` and `!C` constraints * Flag all constraint negation -### T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax +### T.26: Prefer to define concepts in terms of use-patterns rather than simple syntax ##### Reason @@ -11023,11 +11023,11 @@ Conversions are taken into account. You don't have to remember the names of all ??? -## Template interfaces +## Template interfaces ??? -### T.40: Use function objects to pass operations to algorithms +### T.40: Use function objects to pass operations to algorithms ##### Reason @@ -11061,7 +11061,7 @@ The performance argument depends on compiler and optimizer technology. * 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 +### T.41: Require complete sets of operations for a concept ##### Reason @@ -11083,7 +11083,7 @@ The rule supports the view that a concept should reflect a (mathematically) cohe ??? -### T.42: Use template aliases to simplify notation and hide implementation details +### T.42: Use template aliases to simplify notation and hide implementation details ##### Reason @@ -11112,7 +11112,7 @@ This saves the user of `Value_type` from having to know the technique used to im * Flag use of `typename` as a disambiguator outside `using` declarations. * ??? -### T.43: Prefer `using` over `typedef` for defining aliases +### T.43: Prefer `using` over `typedef` for defining aliases ##### Reason @@ -11136,7 +11136,7 @@ Uniformity: `using` is syntactically similar to `auto`. * Flag uses of `typedef`. This will give a lot of "hits" :-( -### T.44: Use function templates to deduce class template argument types (where feasible) +### T.44: Use function templates to deduce class template argument types (where feasible) ##### Reason @@ -11164,7 +11164,7 @@ Sometimes there isn't a good way of getting the template arguments deduced and s 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` +### T.46: Require template arguments to be at least `Regular` or `SemiRegular` ##### Reason @@ -11178,7 +11178,7 @@ Flag uses where an explicitly specialized type exactly matches the types of the ??? -### T.47: Avoid highly visible unconstrained templates with common names +### T.47: Avoid highly visible unconstrained templates with common names ##### Reason @@ -11192,7 +11192,7 @@ Flag uses where an explicitly specialized type exactly matches the types of the ??? -### T.48: If your compiler does not support concepts, fake them with `enable_if` +### T.48: If your compiler does not support concepts, fake them with `enable_if` ##### Reason @@ -11206,7 +11206,7 @@ Flag uses where an explicitly specialized type exactly matches the types of the ??? -### T.49: Where possible, avoid type-erasure +### T.49: Where possible, avoid type-erasure ##### Reason @@ -11222,7 +11222,7 @@ Type erasure incurs an extra level of indirection by hiding type information beh ??? -### T.50: Avoid writing an unconstrained template in the same namespace as a type +### T.50: Avoid writing an unconstrained template in the same namespace as a type ##### Reason @@ -11240,11 +11240,11 @@ This rule should not be necessary; the committee cannot agree on how to fix ADL, ??? 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` -## T.def: Template definitions +## T.def: Template definitions ??? -### T.60: Minimize a template's context dependencies +### T.60: Minimize a template's context dependencies ##### Reason @@ -11262,7 +11262,7 @@ Having a template operate only on its arguments would be one way of reducing the ??? Tricky -### T.61: Do not over-parameterize members (SCARY) +### T.61: Do not over-parameterize members (SCARY) ##### Reason @@ -11328,7 +11328,7 @@ This looks innocent enough, but ??? * 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 +### T.62: Place non-dependent template members in a non-templated base class ##### Reason @@ -11368,7 +11368,7 @@ For N == 1, we have a choice of a base class of a class in the surrounding scope * Flag ??? -### T.64: Use specialization to provide alternative implementations of class templates +### T.64: Use specialization to provide alternative implementations of class templates ##### Reason @@ -11389,7 +11389,7 @@ Specialization offers a powerful mechanism for providing alternative implementat ??? -### T.65: Use tag dispatch to provide alternative implementations of a function +### T.65: Use tag dispatch to provide alternative implementations of a function ##### Reason @@ -11407,7 +11407,7 @@ When `concept`s become available such alternatives can be distinguished directly ??? -### T.66: Use selection using `enable_if` to optionally define a function +### T.66: Use selection using `enable_if` to optionally define a function ##### Reason @@ -11421,7 +11421,7 @@ When `concept`s become available such alternatives can be distinguished directly ??? -### T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point +### T.69: Inside a template, don't make an unqualified nonmember function call unless you intend it to be a customization point ##### Reason @@ -11460,13 +11460,13 @@ There are three major ways to let calling code customize a template. * 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. -## T.temp-hier: Template and hierarchy rules: +## T.temp-hier: Template and hierarchy rules: Templates are the backbone of C++'s support for generic programming and class hierarchies the backbone of its support 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 +### T.80: Do not naively templatize a class hierarchy ##### Reason @@ -11506,7 +11506,7 @@ In many cases you can provide a stable interface by not parameterizing a base; s * Flag virtual functions that depend on a template argument. ??? False positives -### T.81: Do not mix hierarchies and arrays +### T.81: Do not mix hierarchies and arrays ##### Reason @@ -11555,7 +11555,7 @@ Note that the assignment in `maul2()` violated the no-slicing [Rule](#???). * Detect this horror! -### T.82: Linearize a hierarchy when virtual functions are undesirable +### T.82: Linearize a hierarchy when virtual functions are undesirable ##### Reason @@ -11569,7 +11569,7 @@ Note that the assignment in `maul2()` violated the no-slicing [Rule](#???). ??? -### T.83: Do not declare a member function template virtual +### T.83: Do not declare a member function template virtual ##### Reason @@ -11597,7 +11597,7 @@ Double dispatch, visitors, calculate which function to call The compiler handles that. -### T.84: Use a non-template core implementation to provide an ABI-stable interface +### T.84: Use a non-template core implementation to provide an ABI-stable interface ##### Reason @@ -11646,11 +11646,11 @@ Instead of using a separate "base" type, another common technique is to speciali ??? -## T.var: Variadic template rules +## 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 +### T.100: Use variadic templates when you need a function that takes a variable number of arguments of a variety of types ##### Reason @@ -11664,7 +11664,7 @@ Variadic templates is the most general mechanism for that, and is both efficient * Flag uses of `va_arg` in user code. -### T.101: ??? How to pass arguments to a variadic template ??? +### T.101: ??? How to pass arguments to a variadic template ??? ##### Reason @@ -11678,7 +11678,7 @@ Variadic templates is the most general mechanism for that, and is both efficient ??? -### T.102: How to process arguments to a variadic template +### T.102: How to process arguments to a variadic template ##### Reason @@ -11692,7 +11692,7 @@ Variadic templates is the most general mechanism for that, and is both efficient ??? -### T.103: Don't use variadic templates for homogeneous argument lists +### T.103: Don't use variadic templates for homogeneous argument lists ##### Reason @@ -11706,7 +11706,7 @@ There are more precise ways of specifying a homogeneous sequence, such as an `in ??? -## T.meta: Template metaprogramming (TMP) +## T.meta: Template metaprogramming (TMP) Templates provide a general mechanism for compile-time programming. @@ -11714,7 +11714,7 @@ 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 +### T.120: Use template metaprogramming only when you really need to ##### Reason @@ -11743,7 +11743,7 @@ Instead, use concepts. But see [How to emulate concepts if you don't have langua 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 +### T.121: Use template metaprogramming primarily to emulate concepts ##### Reason @@ -11772,7 +11772,7 @@ Such code is much simpler using concepts: ??? -### T.122: Use templates (usually template aliases) to compute types at compile time +### T.122: Use templates (usually template aliases) to compute types at compile time ##### Reason @@ -11790,7 +11790,7 @@ Template metaprogramming is the only directly supported and half-way principled ??? -### T.123: Use `constexpr` functions to compute values at compile time +### T.123: Use `constexpr` functions to compute values at compile time ##### Reason @@ -11818,7 +11818,7 @@ Often a `constexpr` function implies less compile-time overhead than alternative * Flag template metaprograms yielding a value. These should be replaced with `constexpr` functions. -### T.124: Prefer to use standard-library TMP facilities +### T.124: Prefer to use standard-library TMP facilities ##### Reason @@ -11832,7 +11832,7 @@ Facilities defined in the standard, such as `conditional`, `enable_if`, and `tup ??? -### T.125: If you need to go beyond the standard-library TMP facilities, use an existing library +### T.125: If you need to go beyond the standard-library TMP facilities, use an existing library ##### Reason @@ -11847,9 +11847,9 @@ Write your own "advanced TMP support" only if you really have to. ??? -## Other template rules +## Other template rules -### T.140: Name all nontrivial operations +### T.140: Name all nontrivial operations ##### Reason @@ -11876,7 +11876,7 @@ whether functions, lambdas, or operators. ??? -### T.141: Use an unnamed lambda if you need a simple function object in one place only +### T.141: Use an unnamed lambda if you need a simple function object in one place only ##### Reason @@ -11892,7 +11892,7 @@ That makes the code concise and gives better locality than alternatives. * Look for identical and near identical lambdas (to be replaced with named functions or named lambdas). -### T.142?: Use template variables to simplify notation +### T.142?: Use template variables to simplify notation ##### Reason @@ -11906,7 +11906,7 @@ Improved readability. ??? -### T.143: Don't write unintentionally nongeneric code +### T.143: Don't write unintentionally nongeneric code ##### Reason @@ -11964,7 +11964,7 @@ Use the least-derived class that has the functionality you need. * 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 +### T.144: Don't specialize function templates ##### Reason @@ -11980,7 +11980,7 @@ You can't partially specialize a function template per language rules. You can f * Flag all specializations of a function template. Overload instead. -# CPL: C-style programming +# CPL: C-style programming C and C++ are closely related languages. They both originate in "Classic C" from 1978 and have evolved in ISO committees since then. @@ -11992,7 +11992,7 @@ 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 +### CPL.1: Prefer C++ to C ##### Reason @@ -12010,7 +12010,7 @@ It provides better support for high-level programming and often generates faster 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++ +### CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++ ##### Reason @@ -12029,7 +12029,7 @@ That subset can be compiled with both C and C++ compilers, and when compiled as * 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 +### CPL.3: If you must use C for interfaces, use C++ in the calling code using such interfaces ##### Reason @@ -12069,7 +12069,7 @@ You can call C++ from C: None needed -# SF: Source files +# SF: Source files Distinguish between declarations (used as interfaces) and definitions (used as implementations). Use header files to represent interfaces and to emphasize logical structure. @@ -12090,7 +12090,7 @@ 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 +### SF.1: Use a `.cpp` suffix for code files and `.h` for interface files ##### Reason @@ -12126,7 +12126,7 @@ Examples are `.hh` and `.cxx`. Use such names equivalently. * 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 +### SF.2: A `.h` file may not contain object definitions or non-inline function definitions ##### Reason @@ -12153,7 +12153,7 @@ Including entities subject to the one-definition rule leads to linkage errors. Check the positive list above. -### SF.3: Use `.h` files for all declarations used in multiple sourcefiles +### SF.3: Use `.h` files for all declarations used in multiple sourcefiles ##### Reason @@ -12175,7 +12175,7 @@ The user of `bar` cannot know if the interface used is complete and correct. At * Flag declarations of entities in other source files not placed in a `.h`. -### SF.4: Include `.h` files before other declarations in a file +### SF.4: Include `.h` files before other declarations in a file ##### Reason @@ -12208,7 +12208,7 @@ This applies to both `.h` and `.cpp` files. Easy. -### SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface +### SF.5: A `.cpp` file must include the `.h` file(s) that defines its interface ##### Reason @@ -12249,7 +12249,7 @@ The argument-type error for `bar` cannot be caught until link time because of th ??? -### SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope +### SF.6: Use `using`-directives for transition, for foundation libraries (such as `std`), or within a local scope ##### Reason @@ -12263,7 +12263,7 @@ The argument-type error for `bar` cannot be caught until link time because of th ??? -### SF.7: Don't put a `using`-directive in a header file +### SF.7: Don't put a `using`-directive in a header file ##### Reason @@ -12277,7 +12277,7 @@ Doing so takes away an `#include`r's ability to effectively disambiguate and to ??? -### SF.8: Use `#include` guards for all `.h` files +### SF.8: Use `#include` guards for all `.h` files ##### Reason @@ -12295,7 +12295,7 @@ To avoid files being `#include`d several times. Flag `.h` files without `#include` guards. -### SF.9: Avoid cyclic dependencies among source files +### SF.9: Avoid cyclic dependencies among source files ##### Reason @@ -12321,7 +12321,7 @@ Eliminate cycles; don't just break them with `#include` guards. Flag all cycles. -### SF.20: Use `namespace`s to express logical structure +### SF.20: Use `namespace`s to express logical structure ##### Reason @@ -12335,7 +12335,7 @@ Flag all cycles. ??? -### SF.21: Don't use an unnamed (anonymous) namespace in a header +### SF.21: Don't use an unnamed (anonymous) namespace in a header ##### Reason @@ -12349,7 +12349,7 @@ It is almost always a bug to mention an unnamed namespace in a header file. * Flag any use of an anonymous namespace in a header file. -### SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities +### SF.22: Use an unnamed (anonymous) namespace for all internal/nonexported entities ##### Reason @@ -12366,7 +12366,7 @@ An API class and its members can't live in an unnamed namespace; but any "helper * ??? -# SL: The Standard Library +# SL: The Standard Library Using only the bare language, every task is tedious (in any language). Using a suitable library any task can be reasonably simple. @@ -12377,7 +12377,7 @@ Standard-library rule summary: * [SL.2: Prefer the standard library to other libraries](#Rsl-sl) * ??? -### SL.1: Use libraries wherever possible +### SL.1: Use libraries wherever possible ##### Reason @@ -12387,7 +12387,7 @@ Benefit from other people's work when they make improvements. Help other people when you make improvements. -### SL.2: Prefer the standard library to other libraries +### SL.2: Prefer the standard library to other libraries ##### Reason @@ -12401,7 +12401,7 @@ It is more likely to be stable, well-maintained, and widely available than your * [SL.11: Prefer using STL `vector` by default unless you have a reason to use a different container](#Rsl-vector) ??? -### SL.10: Prefer using STL `array` or `vector` instead of a C array +### SL.10: Prefer using STL `array` or `vector` instead of a C array ##### Reason @@ -12427,7 +12427,7 @@ For a variable-length array, use `std::vector`, which additionally can change it * Flag declaration of a C array inside a function or class that also declares an STL container (to avoid excessive noisy warnings on legacy non-STL code). To fix: At least change the C array to a `std::array`. -### SL.11: Prefer using STL `vector` by default unless you have a reason to use a different container +### SL.11: Prefer using STL `vector` by default unless you have a reason to use a different container ##### Reason @@ -12497,23 +12497,23 @@ the choice between `"\\n"` and `endl` is almost completely aesthetic. ### SL.???: printf/scanf -# A: Architectural Ideas +# A: Architectural Ideas This section contains ideas about ??? -### A.1 Separate stable from less stable part of code +### A.1 Separate stable from less stable part of code ??? -### A.2 Express potentially reusable parts as a library +### A.2 Express potentially reusable parts as a library ??? -### A.3 Express potentially separately maintained parts as a library +### A.3 Express potentially separately maintained parts as a library ??? -# Non-Rules and myths +# Non-Rules and myths This section contains rules and guidelines that are popular somewhere, but that we deliberately don't recommend. In the context of the styles of programming we recommend and support with the guidelines, these "non-rules" would do harm. @@ -12527,7 +12527,7 @@ Non-rule summary: * two-phase initialization * goto exit -# RF: References +# RF: References Many coding standards, rules, and guidelines have been written for C++, and especially for specialized uses of C++. Many @@ -12562,7 +12562,7 @@ Reference sections: * [RS.video: Videos about "modern C++"](#SS-vid) * [RF.man: Manuals](#SS-man) -## RF.rules: Coding rules +## RF.rules: Coding rules * [Boost Library Requirements and Guidelines](http://www.boost.org/development/requirements.html). ???. @@ -12601,7 +12601,7 @@ Reference sections: Somewhat brief, pre-C++11, and (not unreasonably) adjusted to its domain. * ??? -## RF.books: Books with coding guidelines +## RF.books: Books with coding guidelines * [Meyers14](#Meyers14) Scott Meyers: Effective Modern C++ (???). Addison-Wesley 2014. Beware of overly technical and overly definite rules. * [SuttAlex05](#SuttAlex05) Sutter and Alexandrescu: C++ Coding Standards. Addison-Wesley 2005. More a set of meta-rules than a set of rules. Pre-C++11. Recommended. @@ -12618,13 +12618,13 @@ Reference sections: Mostly low-level naming and layout rules. Primarily a teaching tool. -## RF.C++: C++ Programming (C++11/C++14) +## RF.C++: C++ Programming (C++11/C++14) * TC++PL4 * Tour++ * Programming: Principles and Practice using C++ -## RF.web: Websites +## RF.web: Websites * [isocpp.org](http://www.isocpp.com) * [Bjarne Stroustrup's home pages](http://www.stroustrup.com) @@ -12633,7 +12633,7 @@ Reference sections: * [Adobe open source](http://www.adobe.com/open-source.html) * [Poco libraries](http://pocoproject.org/) -## RS.video: Videos about "modern C++" +## RS.video: Videos about "modern C++" * Bjarne Stroustrup: [C++11 Style](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style). 2012. * Bjarne Stroustrup: [The Essence of C++: With Examples in C++84, C++98, C++11, and C++14](http://channel9.msdn.com/Events/GoingNative/2013/Opening-Keynote-Bjarne-Stroustrup). 2013 @@ -12642,7 +12642,7 @@ Reference sections: * Sutter: ??? * ??? more ??? -## RF.man: Manuals +## RF.man: Manuals * ISO C++ Standard C++11 * ISO C++ Standard C++14 @@ -12650,7 +12650,7 @@ Reference sections: * ISO C++ Concepts TS * WG21 Ranges report -## Acknowledgements +## Acknowledgements Thanks to the many people who contributed rules, suggestions, supporting information, references, etc.: @@ -12662,7 +12662,7 @@ Thanks to the many people who contributed rules, suggestions, supporting informa * Zhuang, Jiangang (Jeff) * Sergey Zubkov -# Profiles +# Profiles A "profile" is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee. "Deterministic" means they require only local analysis and could be implemented in a compiler (though they don't need to be). "Portably enforceable" means they are like language rules, so programmers can count on enforcement tools giving the same answer for the same code. @@ -12674,7 +12674,7 @@ Profiles summary: * [Pro.bounds: Bounds safety](#SS-bounds) * [Pro.lifetime: Lifetime safety](#SS-lifetime) -## Type safety profile +## Type safety profile This profile makes it easier to construct code that uses types correctly and avoids inadvertent type punning. It does so by focusing on removing the primary sources of type violations, including unsafe uses of casts and unions. @@ -12690,7 +12690,7 @@ 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`. +### Type.1: Don't use `reinterpret_cast`. ##### Reason @@ -12705,7 +12705,7 @@ Use of these casts can violate type safety and cause the program to access a var 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. +### Type.2: Don't use `static_cast` downcasts. Use `dynamic_cast` instead. ##### Reason @@ -12757,7 +12757,7 @@ See also [C.146](#Rh-dynamic_cast). 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). +### Type.3: Don't use `const_cast` to cast away `const` (i.e., at all). ##### Reason @@ -12820,7 +12820,7 @@ Instead, prefer to put the common code in a common helper function -- and make i 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`. +### Type.4: Don't use C-style `(T)expression` casts that would perform a `static_cast` downcast, `const_cast`, or `reinterpret_cast`. ##### Reason @@ -12862,11 +12862,11 @@ Note that a C-style `(T)expression` cast means to perform the first of the follo 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. +### 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. +### Type.6: Always initialize a member variable. ##### Reason @@ -12887,7 +12887,7 @@ Before a variable has been initialized, it does not contain a deterministic vali * 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. +### Type.7: Avoid accessing members of raw unions. Prefer `variant` instead. ##### Reason @@ -12912,7 +12912,7 @@ Note that just copying a union is not type-unsafe, so safe code can pass a union * 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. +### Type.8: Avoid reading from varargs or passing vararg arguments. Prefer variadic template parameters instead. ##### Reason @@ -12945,7 +12945,7 @@ Note: Declaring a `...` parameter is sometimes useful for techniques that don't * 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 of a function that does not offer an overload for a more specific type in the position of the vararg. To fix: Use a different function, or `[[suppress(types)]]`. -## Bounds safety profile +## Bounds safety profile This profile makes it easier to construct code that operates within the bounds of allocated blocks of memory. It does so by focusing on removing the primary sources of bounds violations: pointer arithmetic and array indexing. One of the core features of this profile is to restrict pointers to only refer to single objects, not arrays. @@ -12957,7 +12957,7 @@ 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 `span` instead. +### Bounds.1: Don't use pointer arithmetic. Use `span` instead. ##### Reason @@ -13010,7 +13010,7 @@ Pointers should only refer to single objects, and pointer arithmetic is fragile 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. +### Bounds.2: Only index into arrays using constant expressions. ##### Reason @@ -13096,7 +13096,7 @@ 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. +### Bounds.3: No array-to-pointer decay. ##### Reason @@ -13131,7 +13131,7 @@ Pointers should not be used as arrays. `span` is a bounds-checked, safe alternat 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. +### Bounds.4: Don't use standard library functions and types that are not bounds-checked. ##### Reason @@ -13186,9 +13186,9 @@ If code is using an unmodified standard library, then there are still workaround * We are considering specifying bounds-safe overloads for stdlib (especially C stdlib) functions like `memcmp` and shipping them in the GSL. * For existing stdlib functions and types like `vector` that are not fully bounds-checked, the goal is for these features to be bounds-checked when called from code with the bounds profile on, and unchecked when called from legacy code, possibly using contracts (concurrently being proposed by several WG21 members). -## Lifetime safety profile +## Lifetime safety profile -# GSL: Guideline support library +# GSL: Guideline support library The GSL is a small library of facilities designed to support this set of guidelines. Without these facilities, the guidelines would have to be far more restrictive on language details. @@ -13200,7 +13200,7 @@ Where desirable, they can be "instrumented" with additional functionality (e.g., These Guidelines assume a `variant` type, but this is not currently in GSL because the design is being actively refined in the standards committee. -## GSL.view: Views +## GSL.view: Views These types allow the user to distinguish between owning and non-owning pointers and between pointers to a single object and pointers to the first element of a sequence. @@ -13257,7 +13257,7 @@ French accent optional. Use `not_null` for C-style strings that cannot be `nullptr`. ??? Do we need a name for `not_null`? or is its ugliness a feature? -## GSL.owner: Ownership pointers +## GSL.owner: Ownership pointers * `unique_ptr` // unique ownership: `std::unique_ptr` * `shared_ptr` // shared ownership: `std::shared_ptr` (a counted pointer) @@ -13265,7 +13265,7 @@ Use `not_null` for C-style strings that cannot be `nullptr`. ??? Do we * `dyn_array` // ??? needed ??? A heap-allocated array. The number of elements are determined at construction and fixed thereafter. The elements are mutable unless `T` is a `const` type. Basically a `span` that allocates and owns its elements. -## GSL.assert: Assertions +## GSL.assert: Assertions * `Expects` // precondition assertion. Currently placed in function bodies. Later, should be moved to declarations. // `Expects(p)` terminates the program unless `p == true` @@ -13274,7 +13274,7 @@ Use `not_null` for C-style strings that cannot be `nullptr`. ??? Do we These assertions is currently macros (yuck!) pending standard commission decisions on contracts and assertion syntax. -## GSL.util: Utilities +## GSL.util: Utilities * `finally` // `finally(f)` makes a `final_action{f}` with a destructor that invokes `f` * `narrow_cast` // `narrow_cast(x)` is `static_cast(x)` @@ -13282,7 +13282,7 @@ These assertions is currently macros (yuck!) pending standard commission decisio * `[[implicit]]` // "Marker" to put on single-argument constructors to explicitly make them non-explicit. * `move_owner` // `p = move_owner(q)` means `p = q` but ??? -## GSL.concept: Concepts +## GSL.concept: Concepts These concepts (type predicates) are borrowed from Andrew Sutton's Origin library, the Range proposal, and the ISO WG21 Palo Alto TR. They are likely to be very similar to what will become part of the ISO C++ standard. @@ -13310,12 +13310,12 @@ The notation is that of the ISO WG21 Concepts TS (???ref???). * `Relation` * ... -### Smart pointer concepts +### Smart pointer concepts Described in [Lifetimes paper](https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetimes%20I%20and%20II%20-%20v0.9.1.pdf). -# NL: Naming and layout rules +# NL: Naming and layout rules Consistent naming and layout are helpful. If for no other reason because it minimizes "my style is better than your style" arguments. However, there are many, many, different styles around and people are passionate about them (pro and con). @@ -13345,7 +13345,7 @@ IDEs also tend to have defaults and a range of alternatives.These rules are sugg More specific and detailed rules are easier to enforce. -### NL.1: Don't say in comments what can be clearly stated in code +### NL.1: Don't say in comments what can be clearly stated in code ##### Reason @@ -13361,7 +13361,7 @@ Comments are not updated as consistently as code. 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 +### NL.2: State intent in comments ##### Reason @@ -13379,7 +13379,7 @@ Code says what is done, not what is supposed to be done. Often intent can be sta If the comment and the code disagrees, both are likely to be wrong. -### NL.3: Keep comments crisp +### NL.3: Keep comments crisp ##### Reason @@ -13389,7 +13389,7 @@ Verbosity slows down understanding and makes the code harder to read by spreadin not possible. -### NL.4: Maintain a consistent indentation style +### NL.4: Maintain a consistent indentation style ##### Reason @@ -13406,7 +13406,7 @@ Readability. Avoidance of "silly mistakes." Use a tool. -### NL.5 Don't encode type information in names +### NL.5 Don't encode type information in names **Rationale**: If names reflects type rather than functionality, it becomes hard to change the types used to provide that functionality. Names with types encoded are either verbose or cryptic. @@ -13440,7 +13440,7 @@ Some styles distinguishes types from non-types. This is not evil. -### NL.7: Make the length of a name roughly proportional to the length of its scope +### NL.7: Make the length of a name roughly proportional to the length of its scope **Rationale**: ??? @@ -13452,7 +13452,7 @@ This is not evil. ??? -### NL.8: Use a consistent naming style +### NL.8: Use a consistent naming style **Rationale**: Consistence in naming and naming style increases readability. @@ -13502,7 +13502,7 @@ Try to be consistent in your use of acronyms and lengths of identifiers: Would be possible except for the use of libraries with varying conventions. -### NL 9: Use `ALL_CAPS` for macro names only +### NL 9: Use `ALL_CAPS` for macro names only ##### Reason @@ -13527,7 +13527,7 @@ This rule applies to non-macro symbolic constants: * Flag macros with lower-case letters * Flag `ALL_CAPS` non-macro names -### NL.10: Avoid CamelCase +### NL.10: Avoid CamelCase ##### Reason @@ -13553,7 +13553,7 @@ ISO Standard, but with upper case used for your own types and concepts: Impossible. -### NL.15: Use spaces sparingly +### NL.15: Use spaces sparingly ##### Reason @@ -13585,7 +13585,7 @@ Some IDEs have their own opinions and add distracting space. 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 +### NL.16: Use a conventional class member declaration order ##### Reason @@ -13610,7 +13610,7 @@ Private types and functions can be placed with private data. 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 +### NL.17: Use K&R-derived layout ##### Reason @@ -13678,7 +13678,7 @@ Do not capitalize function names. If you want enforcement, use an IDE to reformat. -### NL.18: Use C++-style declarator layout +### NL.18: Use C++-style declarator layout ##### Reason @@ -13695,7 +13695,7 @@ The use in expressions argument doesn't hold for references. Impossible in the face of history. -### NL.25: Don't use `void` as an argument type +### NL.25: Don't use `void` as an argument type ##### Reason @@ -13717,47 +13717,47 @@ You can make an argument for that abomination in C when function prototypes were would have caused major problems, but not in the 21st century and in C++. -# FAQ: Answers to frequently asked questions +# FAQ: Answers to frequently asked questions This section covers answers to frequently asked questions about these guidelines. -### FAQ.1: What do these guidelines aim to achieve? +### FAQ.1: What do these guidelines aim to achieve? See the top of this page. This is an open source project to maintain modern authoritative guidelines for writing C++ code using the current C++ Standard (as of this writing, C++14). The guidelines are designed to be modern, machine-enforceable wherever possible, and open to contributions and forking so that organizations can easily incorporate them into their own corporate coding guidelines. -### FAQ.2: When and where was this work first announced? +### FAQ.2: When and where was this work first announced? It was announced by [Bjarne Stroustrup in his CppCon 2015 opening keynote, “Writing Good C++14”](https://isocpp.org/blog/2015/09/stroustrup-cppcon15-keynote). See also the [accompanying isocpp.org blog post](https://isocpp.org/blog/2015/09/bjarne-stroustrup-announces-cpp-core-guidelines), and for the rationale of the type and memory safety guidelines see [Herb Sutter’s follow-up CppCon 2015 talk, “Writing Good C++14 ... By Default”](https://isocpp.org/blog/2015/09/sutter-cppcon15-day2plenary). -### FAQ.3: Who are the authors and maintainers of these guidelines? +### FAQ.3: Who are the authors and maintainers of these guidelines? The initial primary authors and maintainers are Bjarne Stroustrup and Herb Sutter, and the guidelines so far were developed with contributions from experts at CERN, Microsoft, Morgan Stanley, and several other organizations. At the time of their release, the guidelines are in a "0.6" state, and contributions are welcome. As Stroustrup said in his announcement: "We need help!" -### FAQ.4: How can I contribute? +### FAQ.4: How can I contribute? See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help! -### FAQ.5: How can I become an editor/maintainer? +### FAQ.5: How can I become an editor/maintainer? By contributing a lot first and having the consistent quality of your contributions recognized. See [CONTRIBUTING.md](https://github.com/isocpp/CppCoreGuidelines/blob/master/CONTRIBUTING.md). We appreciate volunteer help! -### FAQ.6: Have these guidelines been approved by the ISO C++ standards committee? Do they represent the consensus of the committee? +### FAQ.6: Have these guidelines been approved by the ISO C++ standards committee? Do they represent the consensus of the committee? No. These guidelines are outside the standard. They are intended to serve the standard, and be maintained as current guidelines about how to use the current Standard C++ effectively. We aim to keep them in sync with the standard as that is evolved by the committee. -### FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`? +### FAQ.7: If these guidelines are not approved by the committee, why are they under `github.com/isocpp`? Because `isocpp` is the Standard C++ Foundation; the committee’s repositories are under [github.com/*cplusplus*](https://github.com/cplusplus). Some neutral organization has to own the copyright and license to make it clear this is not being dominated by any one person or vendor. The natural entity is the Foundation, which exists to promote the use and up-to-date understanding of modern Standard C++ and the work of the committee. This follows the same pattern that isocpp.org did for the [C++ FAQ](https://isocpp.org/faq), which was initially the work of Bjarne Stroustrup, Marshall Cline, and Herb Sutter and contributed to the open project in the same way. -### FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version? +### FAQ.8: Will there be a C++98 version of these Guidelines? a C++11 version? No. These guidelines are about how to best use Standard C++14 (and, if you have an implementation available, the Concepts Lite Technical Specification) and write code assuming you have a modern conforming compiler. -### FAQ.9: Do these guidelines propose new language features? +### FAQ.9: Do these guidelines propose new language features? No. These guidelines are about how to best use Standard C++14 + the Concepts Lite Technical Specification, and they limit themselves to recommending only those features. -### FAQ.10: What version of Markdown do these guidelines use? +### FAQ.10: What version of Markdown do these guidelines use? These coding standards are written using [CommonMark](http://commonmark.org), and `` HTML anchors. @@ -13770,57 +13770,57 @@ Avoid other HTML tags and other extensions. Note: We are not yet consistent with this style. -### FAQ.50: What is the GSL (guideline support library)? +### FAQ.50: What is the GSL (guideline support library)? The GSL is the small set of types and aliases specified in these guidelines. As of this writing, their specification herein is too sparse; we plan to add a WG21-style interface specification to ensure that different implementations agree, and to propose as a contribution for possible standardization, subject as usual to whatever the committee decides to accept/improve/alter/reject. -### FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL? +### FAQ.51: Is [github.com/Microsoft/GSL](https://github.com/Microsoft/GSL) the GSL? No. That is just a first implementation contributed by Microsoft. Other implementations by other vendors are encouraged, as are forks of and contributions to that implementation. As of this writing one week into the public project, at least one GPLv3 open source implementation already exists. We plan to produce a WG21-style interface specification to ensure that different implementations agree. -### FAQ.52: Why not supply an actual GSL implementation in/with these guidelines? +### FAQ.52: Why not supply an actual GSL implementation in/with these guidelines? We are reluctant to bless one particular implementation because we do not want to make people think there is only one, and inadvertently stifle parallel implementations. And if these guidelines included an actual implementation, then whoever contributed it could be mistakenly seen as too influential. We prefer to follow the long-standing approach of the committee, namely to specify interfaces, not implementations. But at the same time we want at least one implementation available; we hope for many. -### FAQ.53: Why weren’t the GSL types proposed through Boost? +### FAQ.53: Why weren’t the GSL types proposed through Boost? Because we want to use them immediately, and because they are temporary in that we want to retire them as soon as types that fill the same needs exist in the standard library. -### FAQ.54: Has the GSL (guideline support library) been approved by the ISO C++ standards committee? +### FAQ.54: Has the GSL (guideline support library) been approved by the ISO C++ standards committee? No. The GSL exists only to supply a few types and aliases that are not currently in the standard library. If the committee decides on standardized versions (of these or other types that fill the same need) then they can be removed from the GSL. -### FAQ.55: If you’re using the standard types where available, why is the GSL `string_span` different from the `string_view` in the Library Fundamentals 1 Technical Specification? Why not just use the committee-approved `string_view`? +### FAQ.55: If you’re using the standard types where available, why is the GSL `string_span` different from the `string_view` in the Library Fundamentals 1 Technical Specification? Why not just use the committee-approved `string_view`? Because `string_view` is still undergoing standardization, and is in a state for public review input to improve it. Types that appear in Technical Specifications (TSes) are not yet part of the International Standard (IS), and one reason they are put in TSes first is to gain experience with the feature before they are cast in a final form to become part of the standard. Some of the GSL authors are contributing what we have learned about `string_span` in the process of developing these guidelines, and a discussion of the differences between `string_view` and `string_span`, as a paper for the next ISO meeting for consideration along with all the other similar papers for the committee to consider as it decides on the final form of this feature. -### FAQ.56: Is `owner` the same as the proposed `observer_ptr`? +### FAQ.56: Is `owner` the same as the proposed `observer_ptr`? No. `owner` owns, is an alias, and can be applied to any indirection type. The main intent of `observer_ptr` is to signify a *non*-owning pointer. -### FAQ.57: Is `stack_array` the same as the standard `array`? +### FAQ.57: Is `stack_array` the same as the standard `array`? No. `stack_array` is guaranteed to be allocated on the stack. Although a `std::array` contains its storage directly inside itself, the `array` object can be put anywhere, including the heap. -### FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`? +### FAQ.58: Is `dyn_array` the same as `vector` or the proposed `dynarray`? No. `dyn_array` is not resizable, and is a safe way to refer to a heap-allocated fixed-size array. Unlike `vector`, it is intended to replace array-`new[]`. Unlike the `dynarray` that has been proposed in the committee, this does not anticipate compiler/language magic to somehow allocate it on the stack when it is a member of an object that is allocated on the stack; it simply refers to a "dynamic" or heap-based array. -### FAQ.59: Is `Expects` the same as `assert`? +### FAQ.59: Is `Expects` the same as `assert`? No. It is a placeholder for language support for contract preconditions. -### FAQ.60: Is `Ensures` the same as `assert`? +### FAQ.60: Is `Ensures` the same as `assert`? No. It is a placeholder for language support for contract postconditions. -# Appendix A: Libraries +# Appendix A: Libraries This section lists recommended libraries, and explicitly recommends a few. ??? Suitable for the general guide? I think not ??? -# Appendix B: Modernizing code +# Appendix B: Modernizing code Ideally, we follow all rules in all code. Realistically, we have to deal with a lot of old code: @@ -13863,12 +13863,12 @@ The guidelines are not a random set of unrelated rules where you can randomly pi We would dearly love to hear about experience and about tools used. Modernization can be much faster, simpler, and safer when supported with analysis tools and even code transformation tools. -# Appendix C: Discussion +# Appendix C: Discussion This section contains follow-up material on rules and sets of rules. In particular, here we present further rationale, longer examples, and discussions of alternatives. -### Discussion: Define and initialize member variables in the order of member declaration +### Discussion: Define and initialize member variables in the order of member declaration Member variables are always initialized in the order they are declared in the class definition, so write them in that order in the constructor initialization list. Writing them in a different order just makes the code confusing because it won't run in the order you see, and that can make it hard to see order-dependent bugs. @@ -13894,11 +13894,11 @@ If the class definition and the constructor body are in separate files, the long [[Cline99]](#Cline99) §22.03-11, [[Dewhurst03]](Dewhurst03) §52-53, [[Koenig97]](#Koenig97) §4, [[Lakos96]](#Lakos96) §10.3.5, [[Meyers97]](#Meyers97) §13, [[Murray93]](#Murray93) §2.1.3, [[Sutter00]](#Sutter00) §47 -### Use of `=`, `{}`, and `()` as initializers +### Use of `=`, `{}`, and `()` as initializers ??? -### Discussion: Use a factory function if you need "virtual behavior" during initialization +### Discussion: Use a factory function if you need "virtual behavior" during initialization If your design wants virtual dispatch into a derived class from a base class constructor or destructor for functions like `f` and `g`, you need other techniques, such as a post-constructor -- a separate member function the caller must invoke to complete initialization, which can safely call `f` and `g` because in member functions virtual calls behave normally. Some techniques for this are shown in the References. Here's a non-exhaustive list of options: @@ -13961,7 +13961,7 @@ In summary, no post-construction technique is perfect. The worst techniques dodg **References**: [[Alexandrescu01]](#Alexandrescu01) §3, [[Boost]](#Boost), [[Dewhurst03]](#Dewhurst03) §75, [[Meyers97]](#Meyers97) §46, [[Stroustrup00]](#Stroustrup00) §15.4.3, [[Taligent94]](#Taligent94) -### Discussion: Make base class destructors public and virtual, or protected and nonvirtual +### Discussion: Make base class destructors public and virtual, or protected and nonvirtual Should destruction behave virtually? That is, should destruction through a pointer to a `base` class be allowed? If yes, then `base`'s destructor must be public in order to be callable, and virtual otherwise calling it results in undefined behavior. Otherwise, it should be protected so that only derived classes can invoke it in their own destructors, and nonvirtual since it doesn't need to behave virtually virtual. @@ -14032,11 +14032,11 @@ In general, however, avoid concrete base classes (see Item 35). For example, `un **References**: [[C++CS]](#C++CS) Item 50, [[Cargill92]](#Cargill92) pp. 77-79, 207¸ [[Cline99]](#Cline99) §21.06, 21.12-13¸ [[Henricson97]](#Henricson97) pp. 110-114¸ [[Koenig97]](#Koenig97) Chapters 4, 11¸ [[Meyers97]](#Meyers97) §14¸ [[Stroustrup00]](#Stroustrup00) §12.4.2¸ [[Sutter02]](#Sutter02) §27¸ [[Sutter04]](#Sutter04) §18 -### Discussion: Usage of noexcept +### Discussion: Usage of noexcept ??? -### Discussion: Destructors, deallocation, and swap must never fail +### Discussion: Destructors, deallocation, and swap must never fail 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. @@ -14124,7 +14124,7 @@ When using exceptions as your error handling mechanism, always document this beh **References**: [[C++CS]](#C++CS) Item 51; [[C++03]](#C++03) §15.2(3), §17.4.4.8(3)¸ [[Meyers96]](#Meyers96) §11¸ [[Stroustrup00]](#Stroustrup00) §14.4.7, §E.2-4¸ [[Sutter00]](#Sutter00) §8, §16¸ [[Sutter02]](#Sutter02) §18-19 -## Define Copy, move, and destroy consistently +## Define Copy, move, and destroy consistently ##### Reason @@ -14221,7 +14221,7 @@ 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 +### Provide strong resource safety; that is, never leak anything that you think of as a resource ##### Reason @@ -14249,7 +14249,7 @@ This class is a resource handle. It manages the lifetime of the `T`s. To do so, The basic technique for preventing leaks is to have every resource owned by a resource handle with a suitable destructor. A checker can find "naked `new`s". Given a list of C-style allocation functions (e.g., `fopen()`), a checker can also find uses that are not managed by a resource handle. In general, "naked pointers" can be viewed with suspicion, flagged, and/or analyzed. A complete list of resources cannot be generated without human input (the definition of "a resource" is necessarily too general), but a tool can be "parameterized" with a resource list. -### Never throw while holding a resource not owned by a handle +### Never throw while holding a resource not owned by a handle ##### Reason @@ -14294,7 +14294,7 @@ 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 `span` and `string_span` should help a lot (they are not resource handles). -### A "raw" pointer or reference is never a resource handle +### A "raw" pointer or reference is never a resource handle ##### Reason @@ -14304,7 +14304,7 @@ To be able to distinguish owners from views. 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 +### Never let a pointer outlive the object it points to ##### Reason @@ -14332,7 +14332,7 @@ The `string`s of `v` are destroyed upon exit from `bad()` and so is `v` itself. Most compilers already warn about simple cases and has the information to do more. Consider any pointer returned from a function suspect. Use containers, resource handles, and views (e.g., `span` known not to be resource handles) to lower the number of cases to be examined. For starters, consider every class with a destructor as resource handle. -### Use templates to express containers (and other resource handles) +### Use templates to express containers (and other resource handles) ##### Reason @@ -14346,7 +14346,7 @@ To provide statically type-safe manipulation of elements. int sz; }; -### Return containers by value (relying on move or copy elision for efficiency) +### Return containers by value (relying on move or copy elision for efficiency) ##### Reason @@ -14370,7 +14370,7 @@ See the Exceptions in [F.20](#Rf-out). 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 +### If a class is a resource handle, it needs a constructor, a destructor, and copy and/or move operations ##### Reason @@ -14395,7 +14395,7 @@ Now `Named` has a default constructor, a destructor, and efficient copy and move In general, a tool cannot know if a class is a resource handle. However, if a class has some of [the default operations](#SS-ctor), it should have all, and if a class has a member that is a resource handle, it should be considered as resource handle. -### If a class is a container, give it an initializer-list constructor +### If a class is a container, give it an initializer-list constructor ##### Reason @@ -14415,7 +14415,7 @@ It is common to need an initial set of elements. When is a class a container? ??? -# Glossary +# Glossary A relatively informal definition of terms used in the guidelines (based of the glossary in [Programming: Principles and Practice using C++](http://www.stroustrup.com/programming.html)) @@ -14556,7 +14556,7 @@ Simplified definition: a declaration that allocates memory. -# To-do: Unclassified proto-rules +# To-do: Unclassified proto-rules This is our to-do list. Eventually, the entries will become rules or parts of rules.