diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 000000000..87a8648d1
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,20 @@
+name: build
+on: [push, pull_request]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@master
+
+ - name: Install Hunspell
+ run: |
+ sudo apt-get update
+ sudo apt-get install hunspell
+
+ - name: Run cd scripts; make -k
+ run: cd scripts; make -k
+
+ - name: Run cd ..
+ run: cd ..
diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml
new file mode 100644
index 000000000..0ebd768bf
--- /dev/null
+++ b/.github/workflows/jekyll-gh-pages.yml
@@ -0,0 +1,51 @@
+# Sample workflow for building and deploying a Jekyll site to GitHub Pages
+name: Deploy Jekyll with GitHub Pages dependencies preinstalled
+
+on:
+ # Runs on pushes targeting the default branch
+ push:
+ branches: ["master"]
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
+# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
+concurrency:
+ group: "pages"
+ cancel-in-progress: false
+
+jobs:
+ # Build job
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Setup Pages
+ uses: actions/configure-pages@v5
+ - name: Build with Jekyll
+ uses: actions/jekyll-build-pages@v1
+ with:
+ source: ./
+ destination: ./_site
+ - name: Upload artifact
+ uses: actions/upload-pages-artifact@v3
+
+ # Deployment job
+ deploy:
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ needs: build
+ steps:
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..51ce27723
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+scripts/build
+scripts/nodesjs/build
+node_modules
+_site
+scripts/python/__pycache__
+scripts/python/*.pyc
+
+# VS Code
+.vs/
+
+# MacOS-specific
+.DS_Store
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 000000000..4de6f81de
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,22 @@
+# This is the configuration for Travis CI, a free github-integrated service that runs this script for each pull request (if configured)
+
+# provides gcc, clang, make, scons, cmake
+language: c++
+
+# alternatives: gcc, clang, or both (as yaml list)
+compiler: clang
+
+addons:
+ apt:
+ packages:
+ - hunspell
+
+install:
+ -
+
+script:
+ - cd scripts; make -k
+ - cd ..
+
+notifications:
+ email: false
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 7541d6489..51fd05205 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -10,7 +10,7 @@ they can be freely copied and modified to meet your organization's needs.
We encourage contributions to the C++ Core Guidelines in a number of ways:
- **Individual feedback** Are you a developer who is passionate about your code? Join the discussion in
[Issues](https://github.com/isocpp/CppCoreGuidelines/issues). We want to know which rules resonate with you and which don't. Were any rules
-inordinately difficult to apply? Does your compiler vendor's Guideline Support Library (e.g.,
+inordinately difficult to apply? Does your compiler vendor's Guidelines Support Library (e.g.,
[Microsoft's implementation of the GSL](https://github.com/microsoft/gsl)) suit your needs in adopting these guidelines?
- **Organizational adoption** While the guidelines are designed to be broadly adoptable they are also intended to be modified to fit your
organization's particular needs. We encourage your organization to fork this repo and create your own copy of these guidelines with changes
@@ -19,19 +19,19 @@ guidelines and that you provide a link back to the original set of [guidelines](
your local changes are appropriate to pull back into the original guidelines, please open an
[Issue](https://github.com/isocpp/CppCoreGuidelines/issues) which can lead to a pull request.
- **Maintain the Guidelines** The C++ Core Guidelines were created from a wealth of knowledge spread across a number of organizations
-worldwide. If you or your organization is passionate about helping to create the guidelines consider becoming an editor or maintainer. If
-you're a C++ expert who is serious about participating please
-[email coreguidelines@isocpp.org](mailto:coreguidelines@isocpp.org?subject=Maintain the C++ Code Guidelines).
+worldwide. If you or your organization is passionate about helping to create the guidelines, consider becoming an editor or maintainer. If
+you're a C++ expert who is serious about participating, please
+[email coreguidelines@isocpp.org](mailto:coreguidelines@isocpp.org?subject=Maintain%20the%20C++%20Code%20Guidelines).
## Contributor License Agreement
By contributing content to the C++ Core Guidelines (i.e., submitting a pull request for inclusion in this repository) you agree with the
[Standard C++ Foundation](https://isocpp.org/about) [Terms of Use](https://isocpp.org/home/terms-of-use), especially all of the terms specified
regarding Copyright and Patents.
- You warrant that your material is original, or you have the right to contribute it.
-- With respect to the material that you own, you grant a worldwide non-exclusive irrevocable transferable royalty-free license to your contributed
-material to Standard C++ Foundation to display, reproduce, perform, distribute and create derivative works of that material for commercial or
+- With respect to the material that you own, you grant a worldwide, non-exclusive, irrevocable, transferable, and royalty-free license to your contributed
+material to Standard C++ Foundation to display, reproduce, perform, distribute, and create derivative works of that material for commercial or
non-commercial use. With respect to any other material you contribute, such material must be under a license sufficient to allow Standard C++ Foundation
-to display, reproduce, perform, distribute and create derivative works of that material for commercial or non-commercial use.
+to display, reproduce, perform, distribute, and create derivative works of that material for commercial or non-commercial use.
- You agree that, if your contributed material is subsequently reflected in the ISO/IEC C++ standard in any form, it will be subject to all ISO/IEC JTC
1 policies including [copyrights](http://www.iso.org/iso/home/policies.htm),
[patents](http://www.iso.org/iso/home/standards_development/governance_of_technical_work/patents.htm), and
@@ -40,8 +40,59 @@ to display, reproduce, perform, distribute and create derivative works of that m
## Pull requests
-We welcome pull requests for scoped changes to the guidelines--bug fixes in examples, clarifying ambiguous text, etc. Proposed changes should
-first be discussed in the [Issues](https://github.com/isocpp/CppCoreGuidelines/issues) and the Issue number must be included in the pull
-request. Changes should be made in a child commit of a recent commit in the master branch. Lastly, to avoid line ending issues, please
-set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration.
+We welcome pull requests for scoped changes to the guidelines--bug fixes in
+examples, clarifying ambiguous text, etc. Significant changes should first be
+discussed in the [Issues](https://github.com/isocpp/CppCoreGuidelines/issues)
+and the Issue number must be included in the pull request. For
+guideline-related changes, please specify the rule number in your Issue and/or
+Pull Request.
+
+Changes should be made in a child commit of a recent commit in the master
+branch. If you are making many small changes, please create separate PRs to
+minimize merge issues.
+
+### Document Style Guidelines
+
+Documents in this repository are written in an unspecific flavor of Markdown,
+which leaves some ambiguity for formatting text. We ask that pull requests
+maintain the following style guidelines, though we are aware that the document
+may not already be consistent.
+
+#### Indentation
+
+Code and nested text should use multiples of 4 spaces of indentation, and no
+tab characters, like so:
+
+ void func(const int x)
+ {
+ std::cout << x << '\n';
+ }
+
+#### Code Blocks
+
+Please use 4-space indentation to trigger code parsing, rather than [fenced code blocks](https://help.github.com/articles/github-flavored-markdown/#fenced-code-blocks) or any other style, like so:
+
+ This is some document text, with an example below:
+
+ void func()
+ {
+ std::cout << "This is code.\n";
+ }
+
+#### Document style decisions
+
+We've discussed and made decisions on a number of document style. Please do not open PRs that revisit these stylistic points:
+
+- The CppCoreGuidelines.md file is a single GH-flavored Markdown file. It is not split into separate chapters.
+- We do not use syntax highlighting in the Core Guidelines. See PRs #33, #96, #328, and #779. If you want syntax highlighting you
+can either view the "pretty" version at http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines or do your own post-processing.
+- We're sticking with the ASCII character set. We do not use Unicode em-dashes, Unicode spaces, or pretty quotes. Lots of people edit this file with their various text editors. ASCII is simple and universally understood.
+
+### Update dictionary
+
+Code samples in the guidelines are run through a spelling checker. Be sure to add new class and variable names to [scripts/hunspell/isocpp.dic](https://github.com/isocpp/CppCoreGuidelines/blob/master/scripts/hunspell/isocpp.dic).
+
+### Miscellaneous
+
+To avoid line-ending issues, please set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration.
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md
index f28366f73..993bb2663 100644
--- a/CppCoreGuidelines.md
+++ b/CppCoreGuidelines.md
@@ -1,17 +1,16 @@
-
-# C++ Core Guidelines
+# C++ Core Guidelines
-September 9, 2015
+May 8, 2025
Editors:
* [Bjarne Stroustrup](http://www.stroustrup.com)
* [Herb Sutter](http://herbsutter.com/)
-This document is a very early draft. It is inkorrekt, incompleat, and pµøoorly formatted.
-Had it been an open source (code) project, this would have been release 0.6.
+This is a living document under continuous improvement.
+Had it been an open-source (code) project, this would have been release 0.8.
Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
-Contributing to this project requires agreeing to a Contributor License. See the accompanying LICENSE file for details.
+Contributing to this project requires agreeing to a Contributor License. See the accompanying [LICENSE](https://github.com/isocpp/CppCoreGuidelines/blob/master/LICENSE) file for details.
We make this project available to "friendly users" to use, copy, modify, and derive from, hoping for constructive input.
Comments and suggestions for improvements are most welcome.
@@ -21,92 +20,185 @@ The list of contributors is [here](#SS-ack).
Problems:
-* The sets of rules have not been thoroughly checked for completeness, consistency, or enforceability.
-* Triple question marks (???) mark known missing information
+* The sets of rules have not been completely checked for completeness, consistency, or enforceability.
+* Triple question marks (???) mark known missing information.
* Update reference sections; many pre-C++11 sources are too old.
-* For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified)
+* For a more-or-less up-to-date to-do list see: [To-do: Unclassified proto-rules](#S-unclassified).
-You can [Read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
+You can [read an explanation of the scope and structure of this Guide](#S-abstract) or just jump straight in:
+* [In: Introduction](#S-introduction)
* [P: Philosophy](#S-philosophy)
* [I: Interfaces](#S-interfaces)
* [F: Functions](#S-functions)
* [C: Classes and class hierarchies](#S-class)
* [Enum: Enumerations](#S-enum)
+* [R: Resource management](#S-resource)
* [ES: Expressions and statements](#S-expr)
+* [Per: Performance](#S-performance)
+* [CP: Concurrency and parallelism](#S-concurrency)
* [E: Error handling](#S-errors)
-* [R: Resource management](#S-resource)
+* [Con: Constants and immutability](#S-const)
* [T: Templates and generic programming](#S-templates)
-* [CP: Concurrency](#S-concurrency)
-* [STL: The Standard library](#S-stdlib)
-* [SF: Source files](#S-source)
* [CPL: C-style programming](#S-cpl)
-* [PRO: Profiles](#S-profile)
-* [GSL: Guideline support library](#S-gsl)
+* [SF: Source files](#S-source)
+* [SL: The Standard Library](#sl-the-standard-library)
Supporting sections:
-* [NL: Naming and layout](#S-naming)
-* [PER: Performance](#S-performance)
-* [N: Non-Rules and myths](#S-not)
+* [A: Architectural ideas](#S-A)
+* [NR: Non-Rules and myths](#S-not)
* [RF: References](#S-references)
+* [Pro: Profiles](#S-profile)
+* [GSL: Guidelines support library](#gsl-guidelines-support-library)
+* [NL: Naming and layout suggestions](#S-naming)
+* [FAQ: Answers to frequently asked questions](#S-faq)
* [Appendix A: Libraries](#S-libraries)
* [Appendix B: Modernizing code](#S-modernizing)
* [Appendix C: Discussion](#S-discussion)
+* [Appendix D: Supporting tools](#S-tools)
+* [Glossary](#S-glossary)
* [To-do: Unclassified proto-rules](#S-unclassified)
-or look at a specific language feature
-
-* [assignment](#S-???)
-* [`class`](#S-class)
-* [constructor](#SS-ctor)
-* [derived `class`](#SS-hier)
-* [destructor](#SS-ctor)
-* [exception](#S-errors)
-* [`for`](#S-???)
-* [`inline`](#S-class)
-* [initialization](#S-???)
-* [lambda expression](#SS-lambda)
-* [operator](#S-???)
-* [`public`, `private`, and `protected`](#S-???)
-* [`static_assert`](#S-???)
-* [`struct`](#S-class)
-* [`template`](#S-???)
-* [`unsigned`](#S-???)
-* [`virtual`](#S-hier)
-
-Definitions of terms used to express and discuss the rules, that are not language-technical, but refer to design and programming techniques
-
-* error
-* exception
-* failure
-* invariant
-* leak
-* precondition
-* postcondition
-* resource
-* exception guarantee
-
-
-
-# Abstract
+You can sample rules for specific language features:
+
+* assignment:
+[regular types](#Rc-regular) --
+[prefer initialization](#Rc-initialize) --
+[copy](#Rc-copy-semantic) --
+[move](#Rc-move-semantic) --
+[other operations](#Rc-matched) --
+[default](#Rc-eqdefault)
+* `class`:
+[data](#Rc-org) --
+[invariant](#Rc-struct) --
+[members](#Rc-member) --
+[helpers](#Rc-helper) --
+[concrete types](#SS-concrete) --
+[ctors, =, and dtors](#S-ctor) --
+[hierarchy](#SS-hier) --
+[operators](#SS-overload)
+* `concept`:
+[rules](#SS-concepts) --
+[in generic programming](#Rt-raise) --
+[template arguments](#Rt-concepts) --
+[semantics](#Rt-low)
+* constructor:
+[invariant](#Rc-struct) --
+[establish invariant](#Rc-ctor) --
+[`throw`](#Rc-throw) --
+[default](#Rc-default0) --
+[not needed](#Rc-default) --
+[`explicit`](#Rc-explicit) --
+[delegating](#Rc-delegating) --
+[`virtual`](#Rc-ctor-virtual)
+* derived `class`:
+[when to use](#Rh-domain) --
+[as interface](#Rh-abstract) --
+[destructors](#Rh-dtor) --
+[copy](#Rh-copy) --
+[getters and setters](#Rh-get) --
+[multiple inheritance](#Rh-mi-interface) --
+[overloading](#Rh-using) --
+[slicing](#Rc-copy-virtual) --
+[`dynamic_cast`](#Rh-dynamic_cast)
+* destructor:
+[and constructors](#Rc-matched) --
+[when needed?](#Rc-dtor) --
+[must not fail](#Rc-dtor-fail)
+* exception:
+[errors](#S-errors) --
+[`throw`](#Re-throw) --
+[for errors only](#Re-errors) --
+[`noexcept`](#Re-noexcept) --
+[minimize `try`](#Re-catch) --
+[what if no exceptions?](#Re-no-throw-codes)
+* `for`:
+[range-for and for](#Res-for-range) --
+[for and while](#Res-for-while) --
+[for-initializer](#Res-for-init) --
+[empty body](#Res-empty) --
+[loop variable](#Res-loop-counter) --
+[loop variable type ???](#Res-???)
+* function:
+[naming](#Rf-package) --
+[single operation](#Rf-logical) --
+[no throw](#Rf-noexcept) --
+[arguments](#Rf-smart) --
+[argument passing](#Rf-conventional) --
+[multiple return values](#Rf-out-multi) --
+[pointers](#Rf-return-ptr) --
+[lambdas](#Rf-capture-vs-overload)
+* `inline`:
+[small functions](#Rf-inline) --
+[in headers](#Rs-inline)
+* initialization:
+[always](#Res-always) --
+[prefer `{}`](#Res-list) --
+[lambdas](#Res-lambda-init) --
+[default member initializers](#Rc-in-class-initializer) --
+[class members](#Rc-initialize) --
+[factory functions](#Rc-factory)
+* lambda expression:
+[when to use](#SS-lambdas)
+* operator:
+[conventional](#Ro-conventional) --
+[avoid conversion operators](#Ro-conversion) --
+[and lambdas](#Ro-lambda)
+* `public`, `private`, and `protected`:
+[information hiding](#Rc-private) --
+[consistency](#Rh-public) --
+[`protected`](#Rh-protected)
+* `static_assert`:
+[compile-time checking](#Rp-compile-time) --
+[and concepts](#Rt-check-class)
+* `struct`:
+[for organizing data](#Rc-org) --
+[use if no invariant](#Rc-struct) --
+[no private members](#Rc-class)
+* `template`:
+[abstraction](#Rt-raise) --
+[containers](#Rt-cont) --
+[concepts](#Rt-concepts)
+* `unsigned`:
+[and signed](#Res-mix) --
+[bit manipulation](#Res-unsigned)
+* `virtual`:
+[interfaces](#Ri-abstract) --
+[not `virtual`](#Rc-concrete) --
+[destructor](#Rc-dtor-virtual) --
+[never fail](#Rc-dtor-fail)
+
+You can look at design concepts used to express the rules:
+
+* assertion: ???
+* error: ???
+* exception: exception guarantee (???)
+* failure: ???
+* invariant: ???
+* leak: ???
+* library: ???
+* precondition: ???
+* postcondition: ???
+* resource: ???
+
+# 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.
-By "modern C++" we mean C++11 and C++14 (and soon C++17).
+By "modern C++" we mean effective use of the ISO C++ standard (currently C++20, but almost all of our recommendations also apply to C++17, C++14 and C++11).
In other words, what would you like your code to look like in 5 years' time, given that you can start now? In 10 years' time?
-The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management, and concurrency.
+The guidelines are focused on relatively high-level issues, such as interfaces, resource management, memory management, and concurrency.
Such rules affect application architecture and library design.
-Following the rules will lead to code that is statically type safe,
-has no resource leaks, and catches many more programming logic errors than is common in code today.
-And it will run fast - you can afford to do things right.
+Following the rules will lead to code that is statically type safe, has no resource leaks, and catches many more programming logic errors than is common in code today.
+And it will run fast -- you can afford to do things right.
We are less concerned with low-level issues, such as naming conventions and indentation style.
However, no topic that can help a programmer is out of bounds.
-Our initial set of rules emphasize safety (of various forms) and simplicity.
-They may very well be too strict.
+Our initial set of rules emphasizes safety (of various forms) and simplicity.
+They might very well be too strict.
We expect to have to introduce more exceptions to better accommodate real-world needs.
We also need more rules.
@@ -118,9 +210,10 @@ In particular, we'd really like to have some of our rules backed up with measure
You will find some of the rules obvious or even trivial.
Please remember that one purpose of a guideline is to help someone who is less experienced or coming from a different background or language to get up to speed.
-The rules are designed to be supported by an analysis tool.
+Many of the rules are designed to be supported by an analysis tool.
Violations of rules will be flagged with references (or links) to the relevant rule.
We do not expect you to memorize all the rules before trying to write code.
+One way of thinking about these guidelines is as a specification for tools that happens to be readable by humans.
The rules are meant for gradual introduction into a code base.
We plan to build tools for that and hope others will too.
@@ -128,11 +221,9 @@ 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.
+This is a set of core guidelines for modern C++ (currently C++20 and C++17) taking likely future enhancements and ISO Technical Specifications (TSs) into account.
The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
Introduction summary:
@@ -144,54 +235,42 @@ 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++ (currently C++20 and C++17) and to achieve a more uniform style across code bases.
-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.
-
-We do not suffer the delusion that every one of these rules can be effectively applied to every code base.
-Upgrading old systems is hard.
-However, we do believe that a program that uses a rule is less error-prone and more maintainable than one that does not.
-Often, rules also lead to faster/easier initial development.
-As far as we can tell, these rules lead to code that performs as well or better than older, more conventional techniques;
-they are meant to follow the zero-overhead principle
-("what you don't use, you don't pay for" or "When you use an abstraction mechanism appropriately,
-you get at least as good performance as if you had handcoded using lower-level language constructs").
-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.
+We do not suffer the delusion that every one of these rules can be effectively applied to every code base. Upgrading old systems is hard. However, we do believe that a program that uses a rule is less error-prone and more maintainable than one that does not. Often, rules also lead to faster/easier initial development.
+As far as we can tell, these rules lead to code that performs as well or better than older, more conventional techniques; they are meant to follow the zero-overhead principle ("what you don't use, you don't pay for" or "when you use an abstraction mechanism appropriately, you get at least as good performance as if you had handcoded using lower-level language constructs").
+Consider these rules ideals for new code, opportunities to exploit when working on older code, and try to approximate these ideals as closely as feasible.
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.
-These guidelines are designed according to the "subset of a superset" principle ([Stroustrup,2005](#BS2005)).
+These guidelines are designed according to the "subset of superset" principle ([Stroustrup05](#Stroustrup05)).
They do not simply define a subset of C++ to be used (for reliability, safety, performance, or whatever).
-Instead, they strongly recommend the use of a few simple "extensions" ([library components](#S-gsl))
+Instead, they strongly recommend the use of a few simple "extensions" ([library components](#gsl-guidelines-support-library))
that make the use of the most error-prone features of C++ redundant, so that they can be banned (in our set of rules).
The rules emphasize static type safety and resource safety.
For that reason, they emphasize possibilities for range checking, for avoiding dereferencing `nullptr`, for avoiding dangling pointers, and the systematic use of exceptions (via RAII).
-Partly to achieve that and partly to minimize obscure code as a source of errors,
-the rules also emphasize simplicity and the hiding of necessary complexity behind well-specified interfaces.
+Partly to achieve that and partly to minimize obscure code as a source of errors, the rules also emphasize simplicity and the hiding of necessary complexity behind well-specified interfaces.
Many of the rules are prescriptive.
-We are uncomfortable with rules that simply states "don't do that!" without offering an alternative.
+We are uncomfortable with rules that simply state "don't do that!" without offering an alternative.
One consequence of that is that some rules can be supported only by heuristics, rather than precise and mechanically verifiable checks.
Other rules articulate general principles. For these more general rules, more detailed and specific rules provide partial checking.
-These guidelines address a core of C++ and its use.
+These guidelines address the core of C++ and its use.
We expect that most large organizations, specific application areas, and even large projects will need further rules, possibly further restrictions, and further library support.
-For example, hard-real time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
+For example, hard-real-time programmers typically can't use free store (dynamic memory) freely and will be restricted in their choice of libraries.
We encourage the development of such more specific rules as addenda to these core guidelines.
-Build your ideal small foundation library and use that, rather than lowering you level of programming to glorified assembly code.
+Build your ideal small foundation library and use that, rather than lowering your level of programming to glorified assembly code.
The rules are designed to allow [gradual adoption](#S-modernizing).
@@ -199,14 +278,13 @@ 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.
Also, it is often hard to understand the implications of a general rule.
More specialized rules are often easier to understand and to enforce, but without general rules, they would just be a long list of special cases.
-We provide rules aimed as helping novices as well as rules supporting expert use.
+We provide rules aimed at helping novices as well as rules supporting expert use.
Some rules can be completely enforced, but others are based on heuristics.
These rules are not meant to be read serially, like a book.
@@ -221,7 +299,7 @@ If you need a tutorial for some given level of experience, see [the references](
This is not a guide on how to convert old C++ code to more modern code.
It is meant to articulate ideas for new code in a concrete fashion.
However, see [the modernization section](#S-modernizing) for some possible approaches to modernizing/rejuvenating/upgrading.
-Importantly, the rules support gradual adoption: It is typically infeasible to convert all of a large code base at once.
+Importantly, the rules support gradual adoption: It is typically infeasible to completely convert a large code base all at once.
These guidelines are not meant to be complete or exact in every language-technical detail.
For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
@@ -235,56 +313,88 @@ 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.
+The rules are not precise to the point where a person (or machine) can follow them without thinking.
+The enforcement parts try to be that, but we would rather leave a rule or a definition a bit vague
+and open to interpretation than specify something precisely and wrong.
+Sometimes, precision comes only with time and experience.
+Design is not (yet) a form of Math.
+
+The rules are not perfect.
+A rule can do harm by prohibiting something that is useful in a given situation.
+A rule can do harm by failing to prohibit something that enables a serious error in a given situation.
+A rule can do a lot of harm by being vague, ambiguous, unenforceable, or by enabling every solution to a problem.
+It is impossible to completely meet the "do no harm" criteria.
+Instead, our aim is the less ambitious: "Do the most good for most programmers";
+if you cannot live with a rule, object to it, ignore it, but don't water it down until it becomes meaningless.
+Also, suggest an improvement.
-
-## 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.
-But we want lots of rules, and we want rules that everybody can use.
-But different people have different needs.
-But people don't like to read lots of rules.
-But people can't remember many rules.
+
+* But we want lots of rules, and we want rules that everybody can use.
+* But different people have different needs.
+* But people don't like to read lots of rules.
+* But people can't remember many rules.
+
So, we need subsetting to meet a variety of needs.
-But arbitrary subsetting leads to chaos: We want guidelines that help a lot of people, make code more uniform, and strongly encourages people to modernize their code.
+
+* But arbitrary subsetting leads to chaos.
+
+We want guidelines that help a lot of people, make code more uniform, and strongly encourage people to modernize their code.
We want to encourage best practices, rather than leave all to individual choices and management pressures.
The ideal is to use all rules; that gives the greatest benefits.
This adds up to quite a few dilemmas.
We try to resolve those using tools.
Each rule has an **Enforcement** section listing ideas for enforcement.
-Enforcement might be by code review, by static analysis, by compiler, or by run-time checks.
-Wherever possible, we prefer "mechanical" checking (humans are slow and bore easily) and static checking.
-Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed fat" - if that's what you want, you know where to find it.
+Enforcement might be done by code review, by static analysis, by compiler, or by run-time checks.
+Wherever possible, we prefer "mechanical" checking (humans are slow, inaccurate, and bore easily) and static checking.
+Run-time checks are suggested only rarely where no alternative exists; we do not want to introduce "distributed bloat".
Where appropriate, we label a rule (in the **Enforcement** sections) with the name of groups of related rules (called "profiles").
A rule can be part of several profiles, or none.
For a start, we have a few profiles corresponding to common needs (desires, ideals):
-* **types**: No type violations (reinterpreting a `T` as a `U` through casts/unions/varargs)
+* **type**: No type violations (reinterpreting a `T` as a `U` through casts, unions, or varargs)
* **bounds**: No bounds violations (accessing beyond the range of an array)
* **lifetime**: No leaks (failing to `delete` or multiple `delete`) and no access to invalid objects (dereferencing `nullptr`, using a dangling reference).
The profiles are intended to be used by tools, but also serve as an aid to the human reader.
We do not limit our comment in the **Enforcement** sections to things we know how to enforce; some comments are mere wishes that might inspire some tool builder.
+Tools that implement these rules shall respect the following syntax to explicitly suppress a rule:
+
+ [[gsl::suppress("tag")]]
+
+and optionally with a message (following usual C++11 standard attribute syntax):
+
+ [[gsl::suppress("tag", justification: "message")]]
+
+where
-
-## In.struct: The structure of this document
+* `"tag"` is a string literal with the anchor name of the item where the Enforcement rule appears (e.g., for [C.134](#Rh-public) it is "Rh-public"), the
+name of a profile group-of-rules ("type", "bounds", or "lifetime"),
+or a specific rule in a profile ([type.4](#Pro-type-cstylecast), or [bounds.2](#Pro-bounds-arrayindex)). Any text that is not one of those should be rejected.
+
+* `"message"` is a string literal
+
+## In.struct: The structure of this document
Each rule (guideline, suggestion) can have several parts:
-* The rule itself - e.g., **no naked `new`**
-* A rule reference number - e.g., **C.7** (the 7th rule related to classes).
-Since the major sections are not inherently ordered, we use a letter as the first part of a rule reference "number".
-We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
-* **Reason**s (rationales) - because programmers find it hard to follow rules they don't understand
-* **Example**s - because rules are hard to understand in the abstract; can be positive or negative
-* **Alternative**s - for "don't do this" rules
-* **Exception**s - we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
-* **Enforcement** - ideas about how the rule might be checked "mechanically"
-* **See also**s - references to related rules and/or further discussion (in this document or elsewhere)
-* **Note**s (comments) - something that needs saying that doesn't fit the other classifications
-* **Discussion** - references to more extensive rationale and/or examples placed outside the main lists of rules
+* The rule itself -- e.g., **no naked `new`**
+* A rule reference number -- e.g., **C.7** (the 7th rule related to classes).
+ Since the major sections are not inherently ordered, we use letters as the first part of a rule reference "number".
+ We leave gaps in the numbering to minimize "disruption" when we add or remove rules.
+* **Reason**s (rationales) -- because programmers find it hard to follow rules they don't understand
+* **Example**s -- because rules are hard to understand in the abstract; can be positive or negative
+* **Alternative**s -- for "don't do this" rules
+* **Exception**s -- we prefer simple general rules. However, many rules apply widely, but not universally, so exceptions must be listed
+* **Enforcement** -- ideas about how the rule might be checked "mechanically"
+* **See also**s -- references to related rules and/or further discussion (in this document or elsewhere)
+* **Note**s (comments) -- something that needs saying that doesn't fit the other classifications
+* **Discussion** -- references to more extensive rationale and/or examples placed outside the main lists of rules
Some rules are hard to check mechanically, but they all meet the minimal criteria that an expert programmer can spot many violations without too much trouble.
We hope that "mechanical" tools will improve with time to approximate what such an expert programmer notices.
@@ -293,220 +403,269 @@ Also, we assume that the rules will be refined over time to make them more preci
A rule is aimed at being simple, rather than carefully phrased to mention every alternative and special case.
Such information is found in the **Alternative** paragraphs and the [Discussion](#S-discussion) sections.
If you don't understand a rule or disagree with it, please visit its **Discussion**.
-If you feel that a discussion is missing or incomplete, send us an email.
+If you feel that a discussion is missing or incomplete, enter an [Issue](https://github.com/isocpp/CppCoreGuidelines/issues)
+explaining your concerns and possibly a corresponding PR.
+
+Examples are written to illustrate rules.
+
+* Examples are not intended to be production quality or to cover all tutorial dimensions.
+For example, many examples are language-technical and use names like `f`, `base`, and `x`.
+* We try to ensure that "good" examples follow the Core Guidelines.
+* Comments are often illustrating rules where they would be unnecessary and/or distracting in "real code."
+* We assume knowledge of the standard library. For example, we use plain `vector` rather than `std::vector`.
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)
* [I: Interfaces](#S-interfaces)
* [F: Functions](#S-functions)
* [C: Classes and class hierarchies](#S-class)
* [Enum: Enumerations](#S-enum)
+* [R: Resource management](#S-resource)
* [ES: Expressions and statements](#S-expr)
+* [Per: Performance](#S-performance)
+* [CP: Concurrency and parallelism](#S-concurrency)
* [E: Error handling](#S-errors)
-* [R: Resource management](#S-resource)
+* [Con: Constants and immutability](#S-const)
* [T: Templates and generic programming](#S-templates)
-* [CP: Concurrency](#S-concurrency)
-* [STL: The Standard library](#S-stdlib)
-* [SF: Source files](#S-source)
* [CPL: C-style programming](#S-cpl)
-* [PRO: Profiles](#S-profile)
-* [GSL: Guideline support library](#S-gsl)
+* [SF: Source files](#S-source)
+* [SL: The Standard Library](#sl-the-standard-library)
Supporting sections:
-* [NL: Naming and layout](#S-naming)
-* [PER: Performance](#S-performance)
-* [N: Non-Rules and myths](#S-not)
+* [A: Architectural ideas](#S-A)
+* [NR: Non-Rules and myths](#S-not)
* [RF: References](#S-references)
+* [Pro: Profiles](#S-profile)
+* [GSL: Guidelines support library](#gsl-guidelines-support-library)
+* [NL: Naming and layout suggestions](#S-naming)
+* [FAQ: Answers to frequently asked questions](#S-faq)
* [Appendix A: Libraries](#S-libraries)
* [Appendix B: Modernizing code](#S-modernizing)
* [Appendix C: Discussion](#S-discussion)
+* [Appendix D: Supporting tools](#S-tools)
+* [Glossary](#S-glossary)
* [To-do: Unclassified proto-rules](#S-unclassified)
These sections are not orthogonal.
-Each section (e.g., "P" for "Philosophy") and each subsection (e.g., "C.hier" for "Class Hierachies (OOP)") have an abbreviation for ease of searching and reference.
+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.
Philosophy rules summary:
* [P.1: Express ideas directly in code](#Rp-direct)
-* [P.2: Write in ISO Standard C++](#Rp-C++)
+* [P.2: Write in ISO Standard C++](#Rp-Cplusplus)
* [P.3: Express intent](#Rp-what)
* [P.4: Ideally, a program should be statically type safe](#Rp-typesafe)
* [P.5: Prefer compile-time checking to run-time checking](#Rp-compile-time)
* [P.6: What cannot be checked at compile time should be checkable at run time](#Rp-run-time)
* [P.7: Catch run-time errors early](#Rp-early)
-* [P.8: Don't leak any resource](#Rp-leak)
+* [P.8: Don't leak any resources](#Rp-leak)
* [P.9: Don't waste time or space](#Rp-waste)
+* [P.10: Prefer immutable data to mutable data](#Rp-mutable)
+* [P.11: Encapsulate messy constructs, rather than spreading through the code](#Rp-library)
+* [P.12: Use supporting tools as appropriate](#Rp-tools)
+* [P.13: Use support libraries as appropriate](#Rp-lib)
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.
+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**: Compilers don't read comments (or design documents) and neither do many programmers (consistently).
-What is expressed in code has a defined semantics and can (in principle) be checked by compilers and other tools.
+##### Reason
-**Example**:
+Compilers don't read comments (or design documents) and neither do many programmers (consistently).
+What is expressed in code has defined semantics and can (in principle) be checked by compilers and other tools.
- class Date {
- // ...
- public:
- Month month() const; // do
- int month(); // don't
- // ...
- };
+##### Example
+
+ class Date {
+ public:
+ Month month() const; // do
+ int month(); // don't
+ // ...
+ };
The first declaration of `month` is explicit about returning a `Month` and about not modifying the state of the `Date` object.
The second version leaves the reader guessing and opens more possibilities for uncaught bugs.
-**Example**:
-
- void do_something(vector& v)
- {
- string val;
- cin>>val;
- // ...
- int index = 0; // bad
- for(int i=0; i& v)
+ {
+ string val;
+ cin >> val;
+ // ...
+ int index = -1; // bad, plus should use gsl::index
+ for (int i = 0; i < v.size(); ++i) {
+ if (v[i] == val) {
+ index = i;
+ break;
+ }
+ }
+ // ...
+ }
+
+##### Example, good
+
A much clearer expression of intent would be:
- void do_something(vector& v)
- {
- string val;
- cin>>val;
- // ...
- auto p = find(v,val); // better
- // ...
- }
+ void f(vector& v)
+ {
+ string val;
+ cin >> val;
+ // ...
+ auto p = find(begin(v), end(v), val); // better
+ // ...
+ }
A well-designed library expresses intent (what is to be done, rather than just how something is being done) far better than direct use of language features.
-A C++ programmer should know the basics of the STL, and use it where appropriate.
-Any programmer should know the basics of the foundation libraries of the project being worked on, and use it appropriately.
-Any programmer using these guidelines should know the [Guidelines Support Library](#S-gsl), and use it appropriately.
+A C++ programmer should know the basics of the standard library, and use it where appropriate.
+Any programmer should know the basics of the foundation libraries of the project being worked on, and use them appropriately.
+Any programmer using these guidelines should know the [guidelines support library](#gsl-guidelines-support-library), and use it appropriately.
+
+##### Example
-**Example**:
+ change_speed(double s); // bad: what does s signify?
+ // ...
+ change_speed(2.3);
- change_speed(double s); // bad: what does s signify?
- // ...
- change_speed(2.3);
-
A better approach is to be explicit about the meaning of the double (new speed or delta on old speed?) and the unit used:
- change_speed(Speed s); // better: the meaning of s is specified
- // ...
- change_speed(2.3); // error: no unit
- change_speed(23m/10s); // meters per second
+ change_speed(Speed s); // better: the meaning of s is specified
+ // ...
+ change_speed(2.3); // error: no unit
+ change_speed(23_m / 10s); // meters per second
We could have accepted a plain (unit-less) `double` as a delta, but that would have been error-prone.
If we wanted both absolute speed and deltas, we would have defined a `Delta` type.
-
-**Enforcement**: very hard in general.
+
+##### Enforcement
+
+Very hard in general.
* use `const` consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
* flag uses of casts (casts neuter the type system)
* detect code that mimics the standard library (hard)
+### P.2: Write in ISO Standard C++
-
-### P.2: Write in ISO Standard C++
+##### Reason
-**Reason**: This is a set of guidelines for writing ISO Standard C++.
+This is a set of guidelines for writing ISO Standard C++.
-**Note**: There are environments where extensions are necessary, e.g., to access system resources.
-In such cases, localize to use of necessary extensions and control their use with non-core Coding Guidelines.
+##### Note
-**Note**: There are environments where restrictions on use of standard C++ language or library features are necessary,
-e.g., to avoid dynamic memory allocation as required by aircraft control software standards.
-In such cases, control their (dis)use with non-core Coding Guidelines.
+There are environments where extensions are necessary, e.g., to access system resources.
+In such cases, localize the use of necessary extensions and control their use with non-core Coding Guidelines. If possible, build interfaces that encapsulate the extensions so they can be turned off or compiled away on systems that do not support those extensions.
-**Enforcement**: Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions.
-
+Extensions often do not have rigorously defined semantics. Even extensions that
+are common and implemented by multiple compilers might have slightly different
+behaviors and edge case behavior as a direct result of *not* having a rigorous
+standard definition. With sufficient use of any such extension, expected
+portability will be impacted.
-
-### P.3: Express intent
+##### Note
-**Reason**: Unless the intent of some code is stated (e.g., in names or comments), it is impossible to tell whether the code does what it is supposed to do.
+Using valid ISO C++ does not guarantee portability (let alone correctness).
+Avoid dependence on undefined behavior (e.g., [undefined order of evaluation](#Res-order))
+and be aware of constructs with implementation defined meaning (e.g., `sizeof(int)`).
-**Example**:
+##### Note
- int i = 0;
- while (iP.3: Express intent
+
+##### Reason
+
+Unless the intent of some code is stated (e.g., in names or comments), it is impossible to tell whether the code does what it is supposed to do.
+
+##### Example
+
+ gsl::index i = 0;
+ while (i < v.size()) {
+ // ... do something with v[i] ...
+ }
+
+The intent of "just" looping over the elements of `v` is not expressed here. The implementation detail of an index is exposed (so that it might be misused), and `i` outlives the scope of the loop, which might or might not be intended. The reader cannot know from just this section of code.
Better:
- for (auto x : v) { /* do something with x */ }
+ for (const auto& x : v) { /* do something with the value of x */ }
-Now, there is no explicit mention of the iteration mechanism, and the loop operates on a copy of elements so that accidental modification cannot happen. If modification is desired, say so:
+Now, there is no explicit mention of the iteration mechanism, and the loop operates on a reference to `const` elements so that accidental modification cannot happen. If modification is desired, say so:
- for (auto& x : v) { /* do something with x */ }
+ for (auto& x : v) { /* modify x */ }
-Sometimes better still, use a named algorithm:
+For more details about for-statements, see [ES.71](#Res-for-range).
+Sometimes better still, use a named algorithm. This example uses the `for_each` from the Ranges TS because it directly expresses the intent:
- for_each(v,[](int x) { /* do something with x */ });
- for_each(parallel.v,[](int x) { /* do something with x */ });
+ for_each(v, [](int x) { /* do something with the value of x */ });
+ for_each(par, v, [](int x) { /* do something with the value of x */ });
The last variant makes it clear that we are not interested in the order in which the elements of `v` are handled.
A programmer should be familiar with
-* [The guideline support library](#S-gsl)
-* [The ISO C++ standard library](#S-stdlib)
+* [The guidelines support library](#gsl-guidelines-support-library)
+* [The ISO C++ Standard Library](#sl-the-standard-library)
* Whatever foundation libraries are used for the current project(s)
-**Note**: Alternative formulation: Say what should be done, rather than just how it should be done
+##### Note
-**Note**: Some language constructs express intent better than others.
+Alternative formulation: Say what should be done, rather than just how it should be done.
-**Example**: if two `int`s are meant to be the coordinates of a 2D point, say so:
+##### Note
- drawline(int,int,int,int); // obscure
- drawline(Point,Point); // clearer
+Some language constructs express intent better than others.
-**Enforcement**: Look for common patterns for which there are better alternatives
+##### Example
+
+If two `int`s are meant to be the coordinates of a 2D point, say so:
+
+ draw_line(int, int, int, int); // obscure: (x1,y1,x2,y2)? (x,y,h,w)? ...?
+ // need to look up documentation to know
+
+ draw_line(Point, Point); // clearer
+
+##### Enforcement
+
+Look for common patterns for which there are better alternatives
* simple `for` loops vs. range-`for` loops
-* `f(T*,int)` interfaces vs. `f(array_view)` interfaces
-* loop variable in a too large scope
+* `f(T*, int)` interfaces vs. `f(span)` interfaces
+* loop variables in too large a scope
* naked `new` and `delete`
-* functions with many arguments of built-in types
+* functions with many parameters of built-in types
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
-**Reason**: Ideally, a program would be completely statically (compile-time) type safe.
+Ideally, a program would be completely statically (compile-time) type safe.
Unfortunately, that is not possible. Problem areas:
* unions
@@ -515,10159 +674,20252 @@ Unfortunately, that is not possible. Problem areas:
* range errors
* narrowing conversions
-**Note**: These areas are sources of serious problems (e.g., crashes and security violations).
+##### Note
+
+These areas are sources of serious problems (e.g., crashes and security violations).
We try to provide alternative techniques.
-**Enforcement**: We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
+##### Enforcement
+
+We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
Always suggest an alternative.
For example:
-* unions - use `variant`
-* casts - minimize their use; templates can help
-* array decay - use `array_view`
-* range errors - use `array_view`
-* narrowing conversions - minimize their use and use `narrow` or `narrow_cast` where they are necessary
+* unions -- use `variant` (in C++17)
+* casts -- minimize their use; templates can help
+* array decay -- use `span` (from the GSL)
+* range errors -- use `span`
+* narrowing conversions -- minimize their use and use `narrow` or `narrow_cast` (from the GSL) 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
-**Reason**: Code clarity and performance. You don't need to write error handlers for errors caught at compile time.
+Code clarity and performance.
+You don't need to write error handlers for errors caught at compile time.
-**Example**:
+##### Example
- void initializer(Int x)
- // Int is an alias used for integers
- {
- static_assert(sizeof(Int)>=4); // do: compile-time check
+ // Int is an alias used for integers
+ int bits = 0; // don't: avoidable code
+ for (Int i = 1; i; i <<= 1)
+ ++bits;
+ if (bits < 32)
+ cerr << "Int too small\n";
- int bits = 0; // don't: avoidable code
- for (Int i = 1; i; i<<=1)
- ++bits;
- if (bits<32)
- cerr << "Int too small\n";
-
- // ...
- }
+This example fails to achieve what it is trying to achieve (because overflow is undefined) and should be replaced with a simple `static_assert`:
-**Example; don't**:
+ // Int is an alias used for integers
+ static_assert(sizeof(Int) >= 4); // do: compile-time check
- void read(int* p, int n); // read max n integers into *p
-
-**Example**:
+Or better still just use the type system and replace `Int` with `int32_t`.
- void read(array_view r); // read into the range of integers r
+##### Example
-**Alternative formulation**: Don't postpone to run time what can be done well at compile time.
+ void read(int* p, int n); // read max n integers into *p
-**Enforcement**:
+ int a[100];
+ read(a, 1000); // bad, off the end
-* look for pointer arguments
-* look for run-time checks for range violations.
+better
+ void read(span r); // read into the range of integers r
-
-### P.6: What cannot be checked at compile time should be checkable at run time
+ int a[100];
+ read(a); // better: let the compiler figure out the number of elements
-**Reason**: Leaving hard-to-detect errors in a program is asking for crashes and bad results.
+**Alternative formulation**: Don't postpone to run time what can be done well at compile time.
-**Note**: Ideally we catch all errors (that are not errors in the programmer's logic) at either compile-time or run-time. It is impossible to catch all errors at compile time and often not affordable to catch all remaining errors at run time. However, we should endeavor to write programs that in principle can be checked, given sufficient resources (analysis programs, run-time checks, machine resources, time).
+##### Enforcement
-**Example, bad**:
+* Look for pointer arguments.
+* Look for run-time checks for range violations.
- extern void f(int* p); // separately compiled, possibly dynamically loaded
-
- void g(int n)
- {
- f(new int[n]); // bad: the number of elements is not passed to f()
- }
+### P.6: What cannot be checked at compile time should be checkable at run time
-Here, a crucial bit of information (the number of elements) has been so thoroughly "obscured" that static analysis is probably rendered infeasible and dynamic checking can be very difficult when `f()` is part of an ABI so that we cannot "instrument" that pointer. We could embed helpful information into the free store, but that requires global changes to a system and maybe to the compiler. What we have here is a design that makes error detection very hard.
+##### Reason
-**Example, bad**: We can of course pass the number of elements along with the pointer:
+Leaving hard-to-detect errors in a program is asking for crashes and bad results.
- extern void f2(int* p, int n); // separately compiled, possibly dynamically loaded
-
- void g2(int n)
- {
- f2(new int[n],m); // bad: the wrong number of elements can be passed to f()
- }
+##### Note
-Passing the number of elements as an argument is better (and far more common) that just passing the pointer and relying on some (unstated) convention for knowing or discovering the number of elements. However (as shown), a simple typo can introduce a serious error. The connection between the two arguments of `f2()` is conventional, rather than explicit.
+Ideally, we catch all errors (that are not errors in the programmer's logic) at either compile time or run time. It is impossible to catch all errors at compile time and often not affordable to catch all remaining errors at run time. However, we should endeavor to write programs that in principle can be checked, given sufficient resources (analysis programs, run-time checks, machine resources, time).
-Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
+##### Example, bad
-**Example, bad**: The standard library resource management pointers fail to pass the size when they point to an object:
+ // separately compiled, possibly dynamically loaded
+ extern void f(int* p);
- extern void f3(unique_ptr, int n); // separately compiled, possibly dynamically loaded
+ void g(int n)
+ {
+ // bad: the number of elements is not passed to f()
+ f(new int[n]);
+ }
- void g3(int n)
- {
- f3(make_unique(n),m); // bad: pass ownership and size separately
- }
+Here, a crucial bit of information (the number of elements) has been so thoroughly "obscured" that static analysis is probably rendered infeasible and dynamic checking can be very difficult when `f()` is part of an ABI so that we cannot "instrument" that pointer. We could embed helpful information into the free store, but that requires global changes to a system and maybe to the compiler. What we have here is a design that makes error detection very hard.
-**Example**: We need to pass the pointer and the number of elements as an integral object:
+##### Example, bad
- extern void f4(vector&); // separately compiled, possibly dynamically loaded
- extern void f4(array_view); // separately compiled, possibly dynamically loaded
+We can of course pass the number of elements along with the pointer:
- void g3(int n)
- {
- vector v(n);
- f4(v); // pass a reference, retain ownership
- f4(array_view{v}); // pass a view, retain ownership
- }
+ // separately compiled, possibly dynamically loaded
+ extern void f2(int* p, int n);
-This design carries the number of elements along as an integral part of an object, so that errors are unlikely and dynamic (run-time) checking is always feasible, if not always affordable.
+ void g2(int n)
+ {
+ f2(new int[n], m); // bad: a wrong number of elements can be passed to f()
+ }
-**Example**: How do we transfer both ownership and all information needed for validating use?
-
- vector f5(int n) // OK: move
- {
- vector v(n);
- // ... initialize v ...
- return v;
- }
-
- unique_ptr f6(int n) // bad: loses n
- {
- auto p = make_unique(n);
- // ... initialize *p ...
- return p;
- }
-
- owner f7(int n) // bad: loses n and we might forget to delete
- {
- owner p = new int[n];
- // ... initialize *p ...
- return p;
- }
-
-**Example**:
-
- show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
- Or strings as "free-style" options
-
-**Enforcement**:
-
-* Flag (pointer,count) interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
-* ???
+Passing the number of elements as an argument is better (and far more common) than just passing the pointer and relying on some (unstated) convention for knowing or discovering the number of elements. However (as shown), a simple typo can introduce a serious error. The connection between the two arguments of `f2()` is conventional, rather than explicit.
-
-### P.7: Catch run-time errors early
+Also, it is implicit that `f2()` is supposed to `delete` its argument (or did the caller make a second mistake?).
-**Reason**: Avoid "mysterious" crashes.
-Avoid errors leading to (possibly unrecognized) wrong results.
+##### Example, bad
-**Example**:
+The standard library resource management pointers fail to pass the size when they point to an object:
- void increment1(int* p, int n) // bad: error prone
- {
- for (int i=0; i, int n);
- void use1(int m)
- {
- const int n = 10;
- int a[n] = {};
- // ...
- increment1(a,m); // maybe typo, maybe m<=n is supposed
- // but assume that m==20
- // ...
- }
+ void g3(int n)
+ {
+ f3(make_unique(n), m); // bad: pass ownership and size separately
+ }
-Here we made a small error in `use1` that will lead to corrupted data or a crash.
-The (pointer,count) interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
-Assuming that we could check subscripts for out of range access, the error would not be discovered until `p[10]` was accessed.
-We could check earlier and improve the code:
+##### Example
- void increment2(array_view p)
- {
- for (int& x : p) ++x;
- }
-
- void use2(int m)
- {
- const int n = 10;
- int a[n] = {};
- // ...
- increment2({a,m}); // maybe typo, maybe m<=n is supposed
- // ...
- }
-
-Now, `m<=n` can be checked at the point of call (early) rather than later.
-If all we had was a typo so that we meant to use `n` as the bound, the code could be further simplified (eliminating the possibility of an error):
+We need to pass the pointer and the number of elements as an integral object:
- void use3(int m)
- {
- const int n = 10;
- int a[n] = {};
- // ...
- increment2(a); // the number of elements of a need not be repeated
- // ...
- }
-
-**Example, bad**: Don't repeatedly check the same value. Don't pass structured data as strings:
-
- Date read_date(istream& is); // read date from istream
-
- Date extract_date(const string& s); // extract date from string
-
- user1(const string& date) // manipulate date
- {
- auto d = extract_date(date);
- // ...
- }
-
- void user2()
- {
- Date d = read_date(cin);
- // ...
- user1(d.to_string());
- // ...
- }
-
-The date is validated twice (by the `Date` constructor) and passed as an character string (unstructured data).
-
-**Example**: Excess checking can be costly.
-There are cases where checking early is dumb because you may not ever need the value,
-or may only need part of the value that is more easily checked than the whole.
-
- class Jet { // Physics says: e*e < x*x + y*y + z*z
- float fx, fy, fz, fe;
- public:
- Jet(float x, float y, float z, float e)
- :fx(x), fy(y), fz(z), fe(e)
- {
- // Should I check the here that the values are physically meaningful?
- }
-
- float m() const
- {
- // Should I handle the degenerate case here?
- return sqrt(x*x + y*y + z*z - e*e);
- }
-
- ???
- };
-
-The physical law for a jet (`e*e < x*x + y*y + z*z`) is not an invariant because the possibility of measurement errors.
+ extern void f4(vector&); // separately compiled, possibly dynamically loaded
+ extern void f4(span); // separately compiled, possibly dynamically loaded
+ // NB: this assumes the calling code is ABI-compatible, using a
+ // compatible C++ compiler and the same stdlib implementation
-???
+ void g3(int n)
+ {
+ vector v(n);
+ f4(v); // pass a reference, retain ownership
+ f4(span{v}); // pass a view, retain ownership
+ }
-**Enforcement**:
+This design carries the number of elements along as an integral part of an object, so that errors are unlikely and dynamic (run-time) checking is always feasible, if not always affordable.
-* Look at pointers and arrays: Do range-checking early
-* Look at conversions: eliminate or mark narrowing conversions.
-* Look for unchecked values coming from input
-* Look for structured data (objects of classes with invariants) being converted into strings
-* ???
+##### Example
+How do we transfer both ownership and all information needed for validating use?
-
-### P.8: Don't leak any resource
+ vector f5(int n) // OK: move
+ {
+ vector v(n);
+ // ... initialize v ...
+ return v;
+ }
-**Reason**: Essential for long-running programs. Efficiency. Ability to recover from errors.
+ unique_ptr f6(int n) // bad: loses n
+ {
+ auto p = make_unique(n);
+ // ... initialize *p ...
+ return p;
+ }
-**Example, bad**:
+ owner f7(int n) // bad: loses n and we might forget to delete
+ {
+ owner p = new int[n];
+ // ... initialize *p ...
+ return p;
+ }
- void f(char* name)
- {
- FILE* input = fopen(name,"r");
- // ...
- if (something) return; // bad: if something==true, a file handle is leaked
- // ...
- fclose(input);
- }
+##### Example
-Prefer [RAII](#Rr-raii):
+* ???
+* show how possible checks are avoided by interfaces that pass polymorphic base classes around, when they actually know what they need?
+ Or strings as "free-style" options
- void f(char* name)
- {
- ifstream input {name};
- // ...
- if (something) return; // OK: no leak
- // ...
- }
+##### Enforcement
-**See also**: [The resource management section](#S-resources)
+* Flag (pointer, count)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
+* ???
-**Enforcement**:
+### P.7: Catch run-time errors early
-* Look at pointers: classify them into non-owners (the default) and owners.
-Where feasible, replace owners with standard-library resource handles (as in the example above).
-Alternatively, mark an owner as such using `owner` from [the GSL](#S-gsl).
-* Look for naked `new` and `delete`
-* look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
-
-
-
-### P.9: Don't waste time or space
-
-**Reason**: This is C++.
-
-**Note**: Time and space that you spend well to achieve a goal (e.g., speed of development, resource safety, or simplification of testing) is not wasted.
-
-**Example**: ??? more and better suggestions for gratuitous waste welcome ???
-
- struct X {
- char ch;
- int i;
- string s;
- char ch2;
-
- X& operator=(const X& a);
- X(const X&);
- };
-
- X waste(const char* p)
- {
- if (p==nullptr) throw Nullptr_error{};
- int n = strlen(p);
- auto buf = new char[n];
- for (int i = 0; i
-# I: Interfaces
+ void use1(int m)
+ {
+ const int n = 10;
+ int a[n] = {};
+ // ...
+ increment1(a, m); // maybe typo, maybe m <= n is supposed
+ // but assume that m == 20
+ // ...
+ }
-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.
+Here we made a small error in `use1` that will lead to corrupted data or a crash.
+The (pointer, count)-style interface leaves `increment1()` with no realistic way of defending itself against out-of-range errors.
+If we could check subscripts for out of range access, then the error would not be discovered until `p[10]` was accessed.
+We could check earlier and improve the code:
-Interface rule summary:
+ void increment2(span p)
+ {
+ for (int& x : p) ++x;
+ }
-* [I.1: Make interfaces explicit](#Ri-explicit)
-* [I.2: Avoid global variables](#Ri-global)
-* [I.3: Avoid singletons](#Ri-singleton)
-* [I.4: Make interfaces precisely and strongly typed](#Ri-type)
-* [I.5: State preconditions (if any)](#Ri-pre)
-* [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
-* [I.7: State postconditions](#Ri-post)
-* [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
-* [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
-* [I.10: Use exceptions to signal a failure to perform a required tasks](#Ri-except)
-* [I.11: Never transfer ownership by a raw pointer (`T*`)](#Ri-raw)
-* [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
-* [I.13: Do not pass an array as a single pointer](#Ri-array)
-* [I.23: Keep the number of function arguments low](#Ri-nargs)
-* [I.24: Avoid adjacent unrelated parameters of the same type](#Ri-unrelated)
-* [I.25: Prefer abstract classes as interfaces to class hierarchies](#Ri-abstract)
-* [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
+ void use2(int m)
+ {
+ const int n = 10;
+ int a[n] = {};
+ // ...
+ increment2({a, m}); // maybe typo, maybe m <= n is supposed
+ // ...
+ }
-See also
+Now, `m <= n` can be checked at the point of call (early) rather than later.
+If all we had was a typo so that we meant to use `n` as the bound, the code could be further simplified (eliminating the possibility of an error):
-* [F: Functions](#S-functions)
-* [C.concrete: Concrete types](#SS-concrete)
-* [C.hier: Class hierarchies](#SS-hier)
-* [C.over: Overloading and overloaded operators](#SS-overload)
-* [C.con: Containers and other resource handles](#SS-containers)
-* [E: Error handling](#S-errors)
-* [T: Templates and generic programming](#S-templates)
+ void use3(int m)
+ {
+ const int n = 10;
+ int a[n] = {};
+ // ...
+ increment2(a); // the number of elements of a need not be repeated
+ // ...
+ }
-
-### I.1: Make interfaces explicit
+##### Example, bad
-**Reason**: Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
+Don't repeatedly check the same value. Don't pass structured data as strings:
-**Example, bad**:
-Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example,
+ Date read_date(istream& is); // read date from istream
- int rnd(double d)
- {
- return (rnd_up) ? ceil(d) : d; // don't: "invisible" dependency
- }
+ Date extract_date(const string& s); // extract date from string
-It will not be obvious to a caller that the meaning of two calls of `rnd(7.2)` might give different results.
+ void user1(const string& date) // manipulate date
+ {
+ auto d = extract_date(date);
+ // ...
+ }
-**Exception**: Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
-The use of a non-local control is potentially confusing, but controls only implementation details of an otherwise fixed semantics.
+ void user2()
+ {
+ Date d = read_date(cin);
+ // ...
+ user1(d.to_string());
+ // ...
+ }
-**Example, bad**: Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
+The date is validated twice (by the `Date` constructor) and passed as a character string (unstructured data).
- fprintf(connection,"logging: %d %d %d\n",x,y,s); // don't: no test of printf's return value
-
-What if the connection goes down so than no logging output is produced? See Rule I.??.
+##### Example
-**Alternative**: Throw an exception. An exception cannot be ignored.
-
-**Alternative formulation**: Avoid passing information across an interface through non-local state.
-Note that non-`const` member functions pass information to other member functions thorough their object's state.
+Excess checking can be costly.
+There are cases where checking early is inefficient because you might never need the value, or might only need part of the value that is more easily checked than the whole. Similarly, don't add validity checks that change the asymptotic behavior of your interface (e.g., don't add a `O(n)` check to an interface with an average complexity of `O(1)`).
-**Alternative formulation**: An interface should be a function or a set of functions.
-Functions can be template functions and sets of functions can be classes or class templates.
+ class Jet { // Physics says: e * e < x * x + y * y + z * z
+ float x;
+ float y;
+ float z;
+ float e;
+ public:
+ Jet(float x, float y, float z, float e)
+ :x(x), y(y), z(z), e(e)
+ {
+ // Should I check here that the values are physically meaningful?
+ }
-**Enforcement**:
+ float m() const
+ {
+ // Should I handle the degenerate case here?
+ return sqrt(x * x + y * y + z * z - e * e);
+ }
-* (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
+The physical law for a jet (`e * e < x * x + y * y + z * z`) is not an invariant because of the possibility for measurement errors.
-**Reason**: Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
+???
-**Example**:
+##### Enforcement
- struct Data {
- // ... lots of stuff ...
- } data; // non-const data
+* Look at pointers and arrays: Do range-checking early and not repeatedly
+* Look at conversions: Eliminate or mark narrowing conversions
+* Look for unchecked values coming from input
+* Look for structured data (objects of classes with invariants) being converted into strings
+* ???
- void compute() // don't
- {
- // ...use data ...
- }
+### P.8: Don't leak any resources
- void output() // don't
- {
- // ... use data ...
- }
+##### Reason
-Who else might modify `data`?
+Even a slow growth in resources will, over time, exhaust the availability of those resources.
+This is particularly important for long-running programs, but is an essential piece of responsible programming behavior.
-**Note**: global constants are useful.
+##### Example, bad
-**Note**: The rule against global variables applies to namespace scope variables as well.
+ void f(char* name)
+ {
+ FILE* input = fopen(name, "r");
+ // ...
+ if (something) return; // bad: if something == true, a file handle is leaked
+ // ...
+ fclose(input);
+ }
-**Alternative**: If you use global (more generally namespace scope data) to avoid copying, consider passing the data as an object by const reference.
-Another solution is to define the data as the state of some objects and the operations as member functions.
+Prefer [RAII](#Rr-raii):
-**Warning**: Beware of data races: if one thread can access nonlocal data (or data passed by reference) while another thread execute the callee, we can have a data race.
-Every pointer or reference to mutable data is a potential data race.
+ void f(char* name)
+ {
+ ifstream input {name};
+ // ...
+ if (something) return; // OK: no leak
+ // ...
+ }
-**Note**: You cannot have a race condition on immutable data.
+**See also**: [The resource management section](#S-resource)
-**Reference**: See the [rules for calling functions](#SS-call).
+##### Note
-**Enforcement**: (Simple) Report all non-`const` variables declared at namespace scope.
+A leak is colloquially "anything that isn't cleaned up."
+The more important classification is "anything that can no longer be cleaned up."
+For example, allocating an object on the heap and then losing the last pointer that points to that allocation.
+This rule should not be taken as requiring that allocations within long-lived objects must be returned during program shutdown.
+For example, relying on system guaranteed cleanup such as file closing and memory deallocation upon process shutdown can simplify code.
+However, relying on abstractions that implicitly clean up can be as simple, and often safer.
+##### Note
-
-### I.3: Avoid singletons
+Enforcing [the lifetime safety profile](#SS-lifetime) eliminates leaks.
+When combined with resource safety provided by [RAII](#Rr-raii), it eliminates the need for "garbage collection" (by generating no garbage).
+Combine this with enforcement of [the type and bounds profiles](#SS-force) and you get complete type- and resource-safety, guaranteed by tools.
-**Reason**: Singletons are basically complicated global objects in disguise.
+##### Enforcement
-**Example**:
-
- class Singleton {
- // ... lots of stuff to ensure that only one Singleton object is created, that it is initialized properly, etc.
- };
+* Look at pointers: Classify them into non-owners (the default) and owners.
+ Where feasible, replace owners with standard-library resource handles (as in the example above).
+ Alternatively, mark an owner as such using `owner` from [the GSL](#gsl-guidelines-support-library).
+* Look for naked `new` and `delete`
+* Look for known resource allocating functions returning raw pointers (such as `fopen`, `malloc`, and `strdup`)
-There are many variants of the singleton idea.
-That's part of the problem.
-
-**Note**: If you don't want a global object to change, declare it `const` or `constexpr`.
+### P.9: Don't waste time or space
-**Exception**: You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
+##### Reason
- X& myX()
- {
- static X my_x {3};
- return my_x;
- }
+This is C++.
-This one of the most effective solution to problem related to initialization order.
-In a multi-threaded environment the initialization of the static object does not introduce a race condition
-(unless you carelessly access a shared objects from within its constructor).
+##### Note
-If you, as many do, define a singleton as a class for which only one object is created, functions like `myX` are not singletons,
-and this useful technique is not an exception to the no-singleton rule.
-
-**Enforcement**: Very hard in general
+Time and space that you spend well to achieve a goal (e.g., speed of development, resource safety, or simplification of testing) is not wasted.
+"Another benefit of striving for efficiency is that the process forces you to understand the problem in more depth." - Alex Stepanov
-* Look for classes with name that includes `singleton`
-* Look for classes for which only a single object is created (by counting objects or by examining constructors)
+##### Example, bad
+ struct X {
+ char ch;
+ int i;
+ string s;
+ char ch2;
-
-### I.4: Make interfaces precisely and strongly typed
+ X& operator=(const X& a);
+ X(const X&);
+ };
-Reason: Types are the simplest and best documentation, have well-defined meaning, and are guaranteed to be checked at compile time.
-Also, precisely typed code often optimize better.
+ X waste(const char* p)
+ {
+ if (!p) throw Nullptr_error{};
+ int n = strlen(p);
+ auto buf = new char[n];
+ if (!buf) throw Allocation_error{};
+ for (int i = 0; i < n; ++i) buf[i] = p[i];
+ // ... manipulate buffer ...
+ X x;
+ x.ch = 'a';
+ x.s = string(n); // give x.s space for *p
+ for (gsl::index i = 0; i < x.s.size(); ++i) x.s[i] = buf[i]; // copy buf into x.s
+ delete[] buf;
+ return x;
+ }
-**Example; don't**: Consider
+ void driver()
+ {
+ X x = waste("Typical argument");
+ // ...
+ }
- void pass(void* data); // void* is suspicious
+Yes, this is a caricature, but we have seen every individual mistake in production code, and worse.
+Note that the layout of `X` guarantees that at least 6 bytes (and most likely more) are wasted.
+The spurious definition of copy operations disables move semantics so that the return operation is slow
+(please note that the Return Value Optimization, RVO, is not guaranteed here).
+The use of `new` and `delete` for `buf` is redundant; if we really needed a local string, we should use a local `string`.
+There are several more performance bugs and gratuitous complication.
-Now the callee has to cast the data pointer (back) to a correct type to use it. That is error-prone and often verbose.
-Avoid `void*` in interfaces.
-Consider using a variant or a pointer to base instead. (Future note: Consider a pointer to concept.)
+##### Example, bad
-**Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or something like that.
+ void lower(zstring s)
+ {
+ for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
+ }
-**Example; bad**: Consider
+This is actually an example from production code.
+We can see that in our condition we have `i < strlen(s)`. This expression will be evaluated on every iteration of the loop, which means that `strlen` must walk through string every loop to discover its length. While the string contents are changing, it's assumed that `tolower` will not affect the length of the string, so it's better to cache the length outside the loop and not incur that cost each iteration.
- void draw_rect(int,int,int,int); // great opportunities for mistakes
-
- draw_rect(p.x,p.y,10,20); // what does 10,20 mean?
+##### Note
-An `int` can carry arbitrary forms of information, so we must guess about the meaning of the four `int`s.
-Most likely, the first two are an `x`,`y` coordinate pair, but what are the last two?
-Comments and parameter names can help, but we could be explicit:
+An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert.
+However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like.
+The aim of this rule (and the more specific rules that support it) is to eliminate most waste related to the use of C++ before it happens.
+After that, we can look at waste related to algorithms and requirements, but that is beyond the scope of these guidelines.
- void draw_rectangle(Point top_left, Point bottom_right);
- void draw_rectangle(Point top_left, Size height_width);
-
- draw_rectangle(p,Point{10,20}); // two corners
- draw_rectangle(p,Size{10,20}); // one corner and a (height,width) pair
+##### Enforcement
-Obviously, we cannot catch all errors through the static type system
-(e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
-
+Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
-**Example**: ??? units: time duration ???
+* Flag an unused return value from a user-defined non-defaulted postfix `operator++` or `operator--` function. Prefer using the prefix form instead. (Note: "User-defined non-defaulted" is intended to reduce noise. Review this enforcement if it's still too noisy in practice.)
-**Enforcement**:
-* (Simple) Report the use of void* as a parameter or return type.
-* (Hard to do well) Look for member functions with many built-in type arguments
+### P.10: Prefer immutable data to mutable data
+##### Reason
-
-### I.5: State preconditions (if any)
+It is easier to reason about constants than about variables.
+Something immutable cannot change unexpectedly.
+Sometimes immutability enables better optimization.
+You can't have a data race on a constant.
-**Reason**: Arguments have meaning that may constrain their proper use in the callee.
+See [Con: Constants and immutability](#S-const)
-**Example**: Consider
+### P.11: Encapsulate messy constructs, rather than spreading through the code
- double sqrt(double x);
+##### Reason
-Here `x` must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
+Messy code is more likely to hide bugs and harder to write.
+A good interface is easier and safer to use.
+Messy, low-level code breeds more such code.
- double sqrt(double x); // x must be nonnegative
+##### Example
-Some preconditions can be expressed as assertions. For example:
+ int sz = 100;
+ int* p = (int*) malloc(sizeof(int) * sz);
+ int count = 0;
+ // ...
+ for (;;) {
+ // ... read an int into x, exit loop if end of file is reached ...
+ // ... check that x is valid ...
+ if (count == sz)
+ p = (int*) realloc(p, sizeof(int) * sz * 2);
+ p[count++] = x;
+ // ...
+ }
- double sqrt(double x) { Expects(x>=0); /* ... */ }
+This is low-level, verbose, and error-prone.
+For example, we "forgot" to test for memory exhaustion and assign new value to `sz`.
+Instead, we could use `vector`:
-Ideally, that `Expects(x>=0)` should be part of the interface of `sqrt()` but that's not easily done. For now, we place it in the definition (function body).
+ vector v;
+ v.reserve(100);
+ // ...
+ for (int x; cin >> x; ) {
+ // ... check that x is valid ...
+ v.push_back(x);
+ }
-**Reference**: `Expects()` is described in [GSL](#S-gsl).
+##### Note
-**Note**: Prefer a formal specification of requirements, such as `Expects(p!=nullptr);` If that is infeasible, use English text in comments, such as
-`// the sequence [p:q) is ordered using <`
+The standards library and the GSL are examples of this philosophy.
+For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, `gsl::owner`, etc.,
+that are needed to implement key abstractions, such as `vector`, `span`, `lock_guard`, and `future`, we use the libraries
+designed and implemented by people with more time and expertise than we usually have.
+Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves)
+with the challenge of repeatedly getting low-level code well.
+This is a variant of the [subset of superset principle](#R0) that underlies these guidelines.
-**Note**: Most member functions have as a precondition that some class invariant holds.
-That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
-We don't need to mention it for each member function.
+##### Enforcement
-**Enforcement**: (Not enforceable)
+* Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.
-**See also**: the rules for passing pointers.
+### P.12: Use supporting tools as appropriate
-
-### I.6: Prefer `Expects()` for expressing preconditions
+##### Reason
-**Reason**: To make it clear that the condition is a precondition and to enable tool use.
+There are many things that are done better "by machine".
+Computers don't tire or get bored by repetitive tasks.
+We typically have better things to do than repeatedly do routine tasks.
-**Example**:
+##### Example
- int area(int height, int width)
- {
- Expects(height>0 && width>0); // good
- if (height<=0 || width<=0) my_error(); // obscure
- // ...
- }
+Run a static analyzer to verify that your code follows the guidelines you want it to follow.
-**Note**: Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`. This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics (do you always want to abort in debug mode and check nothing in productions runs?).
+##### Note
-**Note**: Preconditions should be part of the interface rather than part of the implementation, but we don't yet have the language facilities to do that.
+See
-**Note**: `Expects()` can also be used to check a condition in the middle of an algorithm.
+* [Static analysis tools](https://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis)
+* [Concurrency tools](#Rconc-tools)
+* [Testing tools](https://github.com/isocpp/CppCoreGuidelines/tree/master)
-**Enforcement**: (Not enforceable) Finding the variety of ways preconditions can be asserted is not feasible. Warning about those that can be easily identified (assert()) has questionable value in the absence of a language facility.
+There are many other kinds of tools, such as source code repositories, build tools, etc.,
+but those are beyond the scope of these guidelines.
+##### Note
-
-### I.7: State postconditions
+Be careful not to become dependent on over-elaborate or over-specialized tool chains.
+Those can make your otherwise portable code non-portable.
-**Reason**: To detect misunderstandings about the result and possibly catch erroneous implementations.
-**Example; bad**: Consider
+### P.13: Use support libraries as appropriate
- int area(int height, int width) { return height*width; } // bad
+##### Reason
-Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
-We also left out the postcondition specification, so it is not obvious that the algorithm (`height*width`) is wrong for areas larger than the largest integer.
-Overflow can happen.
-Consider using:
+Using a well-designed, well-documented, and well-supported library saves time and effort;
+its quality and documentation are likely to be greater than what you could do
+if the majority of your time must be spent on an implementation.
+The cost (time, effort, money, etc.) of a library can be shared over many users.
+A widely used library is more likely to be kept up-to-date and ported to new systems than an individual application.
+Knowledge of a widely-used library can save time on other/future projects.
+So, if a suitable library exists for your application domain, use it.
- int area(int height, int width)
- {
- auto res = height*width;
- Ensures(res>0);
- return res;
- }
+##### Example
-**Example, bad**: Consider a famous security bug
+ std::sort(begin(v), end(v), std::greater<>());
- void f() // problematic
- {
- char buffer[MAX];
- // ...
- memset(buffer,0,MAX);
- }
+Unless you are an expert in sorting algorithms and have plenty of time,
+this is more likely to be correct and to run faster than anything you write for a specific application.
+You need a reason not to use the standard library (or whatever foundational libraries your application uses) rather than a reason to use it.
-There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant `memset()` call:
+##### Note
- void f() // better
- {
- char buffer[MAX];
- // ...
- memset(buffer,0,MAX);
- Ensures(buffer[0]==0);
- }
+By default use
-**Note** postconditions are often informally stated in a comment that states the purpose of a function; `Ensures()` can be used to make this more systematic, visible, and checkable.
+* The [ISO C++ Standard Library](#sl-the-standard-library)
+* The [Guidelines Support Library](#gsl-guidelines-support-library)
-**Note**: Postconditions are especially important when they relate to something that is not directly reflected in a returned result, such as a state of a data structure used.
+##### Note
-**Example**: Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
+If no well-designed, well-documented, and well-supported library exists for an important domain,
+maybe you should design and implement it, and then use it.
- mutex m;
- void manipulate(Record& r) // don't
- {
- m.lock();
- // ... no m.unlock() ...
- }
+# I: Interfaces
-Here, we "forgot" to state that the `mutex` should be released, so we don't know if the failure to ensure release of the `mutex` was a bug or a feature. Stating the postcondition would have made it clear:
+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.
- void manipulate(Record& r) // better: hold the mutex m while and only while manipulating r
- {
- m.lock();
- // ... no m.unlock() ...
- }
+Interface rule summary:
-The bug is now obvious.
+* [I.1: Make interfaces explicit](#Ri-explicit)
+* [I.2: Avoid non-`const` global variables](#Ri-global)
+* [I.3: Avoid singletons](#Ri-singleton)
+* [I.4: Make interfaces precisely and strongly typed](#Ri-typed)
+* [I.5: State preconditions (if any)](#Ri-pre)
+* [I.6: Prefer `Expects()` for expressing preconditions](#Ri-expects)
+* [I.7: State postconditions](#Ri-post)
+* [I.8: Prefer `Ensures()` for expressing postconditions](#Ri-ensures)
+* [I.9: If an interface is a template, document its parameters using concepts](#Ri-concepts)
+* [I.10: Use exceptions to signal a failure to perform a required task](#Ri-except)
+* [I.11: Never transfer ownership by a raw pointer (`T*`) or reference (`T&`)](#Ri-raw)
+* [I.12: Declare a pointer that must not be null as `not_null`](#Ri-nullptr)
+* [I.13: Do not pass an array as a single pointer](#Ri-array)
+* [I.22: Avoid complex initialization of global objects](#Ri-global-init)
+* [I.23: Keep the number of function arguments low](#Ri-nargs)
+* [I.24: Avoid adjacent parameters that can be invoked by the same arguments in either order with different meaning](#Ri-unrelated)
+* [I.25: Prefer empty abstract classes as interfaces to class hierarchies](#Ri-abstract)
+* [I.26: If you want a cross-compiler ABI, use a C-style subset](#Ri-abi)
+* [I.27: For stable library ABI, consider the Pimpl idiom](#Ri-pimpl)
+* [I.30: Encapsulate rule violations](#Ri-encapsulate)
-Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
+**See also**:
- void manipulate(Record& r) // best
- {
- lock_guard _ {m};
- // ...
- }
-
-**Note**: Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
-Only postconditions related to the users can be stated in the interface.
-Postconditions related only to internal state belongs in the definition/implementation.
+* [F: Functions](#S-functions)
+* [C.concrete: Concrete types](#SS-concrete)
+* [C.hier: Class hierarchies](#SS-hier)
+* [C.over: Overloading and overloaded operators](#SS-overload)
+* [C.con: Containers and other resource handles](#SS-containers)
+* [E: Error handling](#S-errors)
+* [T: Templates and generic programming](#S-templates)
-**Enforcement**: (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
+### I.1: Make interfaces explicit
+##### Reason
-
-### I.8: Prefer `Ensures()` for expressing postconditions
+Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
-**Reason**: To make it clear that the condition is a postcondition and to enable tool use.
+##### Example, bad
-**Example**:
+Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
- void f()
- {
- char buffer[MAX];
- // ...
- memset(buffer,0,MAX);
- Ensures(buffer[0]==0);
- }
+ int round(double d)
+ {
+ return (round_up) ? ceil(d) : d; // don't: "invisible" dependency
+ }
-**Note**: postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`. This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.
+It will not be obvious to a caller that the meaning of two calls of `round(7.2)` might give different results.
-**Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
+##### Exception
-Ideally, that `Ensured` should be part of the interface that's not easily done. For now, we place it in the definition (function body).
+Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized.
+The use of a non-local control is potentially confusing, but controls only implementation details of otherwise fixed semantics.
-**Enforcement**: (Not enforceable) Finding the variety of ways postconditions can be asserted is not feasible. Warning about those that can be easily identified (assert()) has questionable value in the absence of a language facility.
+##### Example, bad
+Reporting through non-local variables (e.g., `errno`) is easily ignored. For example:
-
-### I.9: If an interface is a template, document its parameters using concepts
+ // don't: no test of fprintf's return value
+ fprintf(connection, "logging: %d %d %d\n", x, y, s);
-**Reason**: Make the interface precisely specified and compile-time checkable in the (not so distant) future.
+What if the connection goes down so that no logging output is produced? See I.???.
-**Example**: Use the ISO Concepts TS style of requirements specification. For example:
+**Alternative**: Throw an exception. An exception cannot be ignored.
- template
- // requires InputIterator && EqualityComparable>,Val>
- Iter find(Iter first, Iter last, Val v)
- {
- // ...
- }
+**Alternative formulation**: Avoid passing information across an interface through non-local or implicit state.
+Note that non-`const` member functions pass information to other member functions through their object's state.
-**Note**: Soon (maybe in 2016), most compilers will be able to check `requires` clauses once the `//` is removed.
+**Alternative formulation**: An interface should be a function or a set of functions.
+Functions can be function templates and sets of functions can be classes or class templates.
-**See also**: See [generic programming](???) and [???](???)
+##### Enforcement
-**Enforcement**: (Not enforceable yet) A language facility is under specification. When the language facility is available, warn if any non-variadic template parameter is not constrained by a concept (in its declaration or mentioned in a `requires` clause.
+* (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 non-`const` global variables
-
-### I.10: Use exceptions to signal a failure to perform an required task
+##### Reason
-**Reason**: It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
-This is a major source of errors.
+Non-`const` global variables hide dependencies and make the dependencies subject to unpredictable changes.
-**Example**:
+##### Example
- int printf(const char* ...); // bad: return negative number if output fails
+ struct Data {
+ // ... lots of stuff ...
+ } data; // non-const data
- template
- explicit thread(F&& f, Args&&... args); // good: throw system_error if unable to start the new thread
+ void compute() // don't
+ {
+ // ... use data ...
+ }
-
-**Note**: What is an error?
-An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
-Calling code that ignores the error could lead to wrong results or undefined systems state.
-For example, not being able to connect to a remote server is not by itself an error:
-the server can refuse a connection for all kinds of reasons, so the natural thing is to return a result that the caller always has to check.
-However, if failing to make a connection is considered an error, then a failure should throw an exception.
+ void output() // don't
+ {
+ // ... use data ...
+ }
-**Exception**: Many traditional interface functions (e.g., UNIX signal handlers) use error codes (e.g., `errno`) to report what are really status codes, rather than errors. You don't have good alternative to using such, so calling these does not violate the rule.
+Who else might modify `data`?
-**Alternative**: If you can't use exceptions (e.g. because your code is full of old-style raw-pointer use or because there are hard-real-time constraints),
-consider using a style that returns a pair of values:
+**Warning**: The initialization of global objects is not totally ordered.
+If you use a global object initialize it with a constant.
+Note that it is possible to get undefined initialization order even for `const` objects.
- int val;
- int error_code;
- tie(val,error_code) = do_something();
- if (error_code==0) {
- // ... handle the error or exit ...
- }
- // ... use val ...
+##### Exception
-**Note**: We don't consider "performance" a valid reason not to use exceptions.
+A global object is often better than a singleton.
-* Often, explicit error checking and handling consume as much time and space as exception handling.
-* Often, cleaner code yield better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
-* A good rule for performance critical code is to move checking outside the critical part of the code ([checking](#Rper-checking)).
-* In the longer term, more regular code gets better optimized.
+##### Note
-**See also**: Rule I.??? and I.??? for reporting precondition and postcondition violations.
+Global constants are useful.
-**Enforcement**:
+##### Note
-* (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
-* look for `errno`.
+The rule against global variables applies to namespace scope variables as well.
+**Alternative**: If you use global (more generally namespace scope) data to avoid copying, consider passing the data as an object by reference to `const`.
+Another solution is to define the data as the state of some object and the operations as member functions.
-
-### I.11: Never transfer ownership by a raw pointer (`T*`)
+**Warning**: Beware of data races: If one thread can access non-local data (or data passed by reference) while another thread executes the callee, we can have a data race.
+Every pointer or reference to mutable data is a potential data race.
-**Reason**: if there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
+Using global pointers or references to access and change non-const, and otherwise non-global,
+data isn't a better alternative to non-const global variables since that doesn't solve the issues of hidden dependencies or potential race conditions.
-**Example**: Consider
+##### Note
- X* compute(args) // don't
- {
- X* res = new X{};
- // ...
- return res;
- }
+You cannot have a race condition on immutable data.
-Who deletes the returned `X`? The problem would be harder to spot if compute returned a reference.
-Consider returning the result by value (use move semantics if the result is large):
+**References**: See the [rules for calling functions](#SS-call).
- vector compute(args) // good
- {
- vector res(10000);
- // ...
- return res;
- }
+##### Note
-**Alternative**: Pass ownership using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
-However that is less elegant and less efficient unless reference semantics are needed.
+The rule is "avoid", not "don't use." Of course there will be (rare) exceptions, such as `cin`, `cout`, and `cerr`.
-**Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
-In that case, mark owning pointers using `owner` :
+##### Enforcement
- owner compute(args) // It is now clear that ownership is transferred
- {
- owner res = new X{};
- // ...
- return res;
- }
+(Simple) Report all non-`const` variables declared at namespace scope and global pointers/references to non-const data.
-This tells analysis tools that `res` is an owner.
-That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
-`owner` is used similarly in the implementation of resource handles.
+### I.3: Avoid singletons
-`owner` is defined in the [Guideline Support Library](#S-gsl).
+##### Reason
-**Note**: Every object passed as a raw pointer (or iterator) is assumed to be owned by the caller, so that its lifetime is handled by the caller.
+Singletons are basically complicated global objects in disguise.
-**See also**: [Argument passing](#Rf-conventional) and [value return](#Rf-T-return).
+##### Example
-**Enforcement**:
+ class Singleton {
+ // ... lots of stuff to ensure that only one Singleton object is created,
+ // that it is initialized properly, etc.
+ };
-* (Simple) Warn on `delete` of a raw pointer that is not an `owner`.
-* (Simple) Warn on failure to either `reset` or explicitly `delete` an `owner` pointer on every code path.
-* (Simple) Warn if the return value of `new` or a function call with return value of pointer type is assigned to a raw pointer.
+There are many variants of the singleton idea.
+That's part of the problem.
+##### Note
-
-### I.12: Declare a pointer that must not be null as `not_null`
+If you don't want a global object to change, declare it `const` or `constexpr`.
-**Reason**: To help avoid dereferencing `nullptr` errors. To improve performance by avoiding redundant checks for `nullptr`.
+##### Exception
-**Example**:
+You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:
- int length(const char* p); // it is not clear whether strlen(nullptr) is valid
+ X& myX()
+ {
+ static X my_x {3};
+ return my_x;
+ }
- length(nullptr); // OK?
+This is one of the most effective solutions to problems related to initialization order.
+In a multi-threaded environment, the initialization of the static object does not introduce a race condition
+(unless you carelessly access a shared object from within its constructor).
- int length(not_null p); // better: we can assume that p cannot be nullptr
+Note that the initialization of a local `static` does not imply a race condition.
+However, if the destruction of `X` involves an operation that needs to be synchronized we must use a less simple solution.
+For example:
- int length(const char* p); // we must assume that p can be nullptr
+ X& myX()
+ {
+ static auto p = new X {3};
+ return *p; // potential leak
+ }
-By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.
+Now someone must `delete` that object in some suitably thread-safe way.
+That's error-prone, so we don't use that technique unless
-**Note**: The assumption that the pointer to `char` pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use `zstring` in preference to `const char*`.
+* `myX` is in multi-threaded code,
+* that `X` object needs to be destroyed (e.g., because it releases a resource), and
+* `X`'s destructor's code needs to be synchronized.
- int length(not_null p); // we can assume that p cannot be nullptr
- // we can assume that p points to a zero-terminated array of characters
+If you, as many do, define a singleton as a class for which only one object is created, functions like `myX` are not singletons, and this useful technique is not an exception to the no-singleton rule.
-Note: `length()` is, of course, `std::strlen()` in disguise.
+##### Enforcement
-**Enforcement**:
+Very hard in general.
-* (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`.
+* Look for classes with names that include `singleton`.
+* 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.13: Do not pass an array as a single pointer
+##### Reason
-**Reason**: (pointer,size)-style interfaces are error-prone. Also, plain pointer (to array) must relies on some convention to allow the callee to determine the size.
+Types are the simplest and best documentation, improve legibility due to their well-defined meaning, and are checked at compile time.
+Also, precisely typed code is often optimized better.
-**Example**: Consider
+##### Example, don't
- void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
+Consider:
-What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
-What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
-Either is undefined behavior and a potentially very nasty bug.
+ void pass(void* data); // weak and under qualified type void* is suspicious
-**Alternative**: Consider using explicit ranges,
+Callers are unsure what types are allowed and if the data may
+be mutated as `const` is not specified. Note all pointer types
+implicitly convert to `void*`, so it is easy for callers to provide this value.
- void copy(array_view r, array_view r2); // copy r to r2
+The callee must `static_cast` data to an unverified type to use it.
+That is error-prone and verbose.
-**Example, bad**: Consider
+Only use `const void*` for passing in data in designs that are indescribable in C++. Consider using a `variant` or a pointer to base instead.
- void draw(Shape* p, int n); // poor interface; poor code
- Circle arr[10];
- // ...
- draw(arr,10);
+**Alternative**: Often, a template parameter can eliminate the `void*` turning it into a `T*` or `T&`.
+For generic code these `T`s can be general or concept constrained template parameters.
-Passing `10` as the `n` argument may be a mistake: the most common convention is to assume [`0`:`n`) but that is nowhere stated. Worse is that the call of `draw()` compiled at all: there was an implicit conversion from array to pointer (array decay) and then another implicit conversion from `Circle` to `Shape`. There is no way that `draw()` can safely iterate through that array: it has no way of knowing the size of the elements.
+##### Example, bad
-**Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
+Consider:
- void draw2(array_view);
- Circle arr[10];
- // ...
- draw2(array_view(arr)); // deduce the number of elements
- draw2(arr); // deduce the element type and array size
+ draw_rect(100, 200, 100, 500); // what do the numbers specify?
- void draw3(array_view);
- draw3(arr); // error: cannot convert Circle[10] to array_view
+ draw_rect(p.x, p.y, 10, 20); // what units are 10 and 20 in?
-This `draw2()` passes the same amount of information to `draw()`, but makes the fact that it is supposed to be a range of `Circle`s explicit. See ???.
+It is clear that the caller is describing a rectangle, but it is unclear what parts they relate to. Also, an `int` can carry arbitrary forms of information, including values of many units, so we must guess about the meaning of the four `int`s. Most likely, the first two are an `x`,`y` coordinate pair, but what are the last two?
-**Exception**: Use `zstring` and `czstring` to represent a C-style, zero-terminated strings. But see ???.
+Comments and parameter names can help, but we could be explicit:
-**Enforcement**:
+ void draw_rectangle(Point top_left, Point bottom_right);
+ void draw_rectangle(Point top_left, Size height_width);
-* (Simple) ((Bounds)) Warn for any expression that would rely on implicit conversion of an array type to a pointer type. Allow exception for zstring/czstring pointer types.
-* (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. Allow exception for zstring/czstring pointer types.
+ draw_rectangle(p, Point{10, 20}); // two corners
+ draw_rectangle(p, Size{10, 20}); // one corner and a (height, width) pair
+Obviously, we cannot catch all errors through the static type system
+(e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).
-
-### I.14: Keep the number of function arguments low
+##### Example, bad
-**Reason**: Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
+Consider:
-**Example**: The standard-library `merge()` is at the limit of what we can comfortably handle
+ set_settings(true, false, 42); // what do the numbers specify?
- template
- OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
- InputIterator2 first2, InputIterator2 last2,
- OutputIterator result, Compare comp);
+The parameter types and their values do not communicate what settings are being specified or what those values mean.
-Here, we have four template arguments and six function arguments.
-To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
+This design is more explicit, safe and legible:
- template
- OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
- InputIterator2 first2, InputIterator2 last2,
- OutputIterator result);
+ alarm_settings s{};
+ s.enabled = true;
+ s.displayMode = alarm_settings::mode::spinning_light;
+ s.frequency = alarm_settings::every_10_seconds;
+ set_settings(s);
-This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
-To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
+For the case of a set of boolean values consider using a flags `enum`; a pattern that expresses a set of boolean values.
- template
- OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
+ enable_lamp_options(lamp_option::on | lamp_option::animate_state_transitions);
-Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
+##### Example, bad
-**Note**: How many arguments are too many? Four arguments is a lot.
-There are functions that are best expressed with four individual arguments, but not many.
+In the following example, it is not clear from the interface what `time_to_blink` means: Seconds? Milliseconds?
-**Alternative**: Group arguments into meaningful objects and pass the objects (by value or by reference).
+ void blink_led(int time_to_blink) // bad -- the unit is ambiguous
+ {
+ // ...
+ // do something with time_to_blink
+ // ...
+ }
-**Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
+ void use()
+ {
+ blink_led(2);
+ }
-**Enforcement**:
- - Warn when a functions declares two iterators (including pointers) of the same type instead of a range or a view.
- - (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
+##### Example, good
+`std::chrono::duration` types helps making the unit of time duration explicit.
-
-### I.15: Avoid adjacent unrelated parameters of the same type
+ void blink_led(milliseconds time_to_blink) // good -- the unit is explicit
+ {
+ // ...
+ // do something with time_to_blink
+ // ...
+ }
-**Reason**: Adjacent arguments of the same type are easily swapped by mistake.
+ void use()
+ {
+ blink_led(1500ms);
+ }
-**Example; bad**: Consider
+The function can also be written in such a way that it will accept any time duration unit.
- void copy_n(T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
+ template
+ void blink_led(duration time_to_blink) // good -- accepts any unit
+ {
+ // assuming that millisecond is the smallest relevant unit
+ auto milliseconds_to_blink = duration_cast(time_to_blink);
+ // ...
+ // do something with milliseconds_to_blink
+ // ...
+ }
-This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
+ void use()
+ {
+ blink_led(2s);
+ blink_led(1500ms);
+ }
-Use `const` for the "from" argument:
+##### Enforcement
- void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
+* (Simple) Report the use of `void*` as a parameter or return type.
+* (Simple) Report the use of more than one `bool` parameter.
+* (Hard to do well) Look for functions that use too many primitive type arguments.
-**Alternative**: Don't pass arrays as pointers, pass an object representing a range (e.g., an `array_view`):
+### I.5: State preconditions (if any)
- void copy_n(array_view p, array_view q); // copy from b to q
+##### Reason
-**Enforcement**: (Simple) Warn if two consecutive parameters share the same type.
+Arguments have meaning that might constrain their proper use in the callee.
+##### Example
-
-### I.16: Prefer abstract classes as interfaces to class hierarchies
+Consider:
-**Reason**: Abstract classes are more likely to be stable than base classes with state.
+ double sqrt(double x);
-**Example; bad**: You just knew that `Shape` would turn up somewhere :-)
+Here `x` must be non-negative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
- class Shape { // bad: interface class loaded with data
- public:
- Point center() { return c; }
- virtual void draw();
- virtual void rotate(int);
- // ...
- private:
- Point c;
- vector outline;
- Color col;
- };
+ double sqrt(double x); // x must be non-negative
-This will force every derived class to compute a center -- even if that's non-trivial and the center is never used. Similarly, not every `Shape` has a `Color`, and many `Shape`s are best represented without an outline defined as a sequence of `Point`s. Abstract classes were invented to discourage users from writing such classes:
+Some preconditions can be expressed as assertions. For example:
- class Shape { // better: Shape is a pure interface
- public:
- virtual Point center() =0; // pure virtual function
- virtual void draw() =0;
- virtual void rotate(int) =0;
- // ...
- // ... no data members ...
- };
+ double sqrt(double x) { Expects(x >= 0); /* ... */ }
-**Enforcement**: (Simple) Warn if a pointer to a class `C` is assigned to a pointer to a base of `C` and the base class contains data members.
+Ideally, that `Expects(x >= 0)` should be part of the interface of `sqrt()` but that's not easily done. For now, we place it in the definition (function body).
+**References**: `Expects()` is described in [GSL](#gsl-guidelines-support-library).
-
-### I.16: If you want a cross-compiler ABI, use a C-style subset
+##### Note
-**Reason**: Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
+Prefer a formal specification of requirements, such as `Expects(p);`.
+If that is infeasible, use English text in comments, such as `// the sequence [p:q) is ordered using <`.
-**Exception**: You can carefully craft an interface using a few carefully selected higher-level C++ types. See ???.
+##### Note
-**Exception**: Common ABIs are emerging on some platforms freeing you from the more Draconian restrictions.
+Most member functions have as a precondition that some class invariant holds.
+That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class.
+We don't need to mention it for each member function.
-**Note**: if you use a single compiler, you can use full C++ in interfaces. That may require recompilation after an upgrade to a new compiler version.
+##### Enforcement
-**Enforcement**: (Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
+(Not enforceable)
+**See also**: The rules for passing pointers. ???
-
-# F: Functions
+### I.6: Prefer `Expects()` for expressing preconditions
-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.
+##### Reason
-It should be possible to name a function meaningfully, to specify the requirements of its argument, and clearly state the relationship between the arguments and the result. An implementation is not a specification. Try to think about what a function does as well as about how it does it.
-Functions are the most critical part in most interfaces, so see the interface rules.
+To make it clear that the condition is a precondition and to enable tool use.
-Function rule summary:
+##### Example
-Function definition rules:
+ int area(int height, int width)
+ {
+ Expects(height > 0 && width > 0); // good
+ if (height <= 0 || width <= 0) my_error(); // obscure
+ // ...
+ }
-* [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
-* [F.2: A function should perform a single logical operation](#Rf-logical)
-* [F.3: Keep functions short and simple](#Rf-single)
-* [F.4: If a function may have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
-* [F.5: If a function is very small and time critical, declare it inline](#Rf-inline)
-* [F.6: If your function may not throw, declare it `noexcept`](#Rf-noexcept)
-* [F.7: For general use, take `T*` arguments rather than a smart pointers](#Rf-smart)
-* [F.8: Prefer pure functions](#Rf-pure)
+##### Note
-Argument passing rules:
+Preconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
+This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and might have the wrong semantics (do you always want to abort in debug mode and check nothing in productions runs?).
-* [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
-* [F.16: Use `T*` or `owner` or a smart pointer to designate a single object](#Rf-ptr)
-* [F.17: Use a `not_null` to indicate "null" is not a valid value](#Rf-nullptr)
-* [F.18: Use an `array_view` or an `array_view_p` to designate a half-open sequence](#Rf-range)
-* [F.19: Use a `zstring` or a `not_null` to designate a C-style string](#Rf-string)
-* [F.20: Use a `const T&` parameter for a large object](#Rf-const-T-ref)
-* [F.21: Use a `T` parameter for a small object](#Rf-T)
-* [F.22: Use `T&` for an in-out-parameter](#Rf-T-re)
-* [F.23: Use `T&` for an out-parameter that is expensive to move (only)](#Rf-T-return-out)
-* [F.24: Use a `TP&&` parameter when forwarding (only)](#Rf-pass-ref-ref)
-* [F.25: Use a `T&&` parameter together with `move` for rare optimization opportunities](#Rf-pass-ref-move)
-* [F.26: Use a `unique_ptr` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
-* [F.27: Use a `shared_ptr` to share ownership](#Rf-shared_ptr)
+##### Note
-Value return rules:
+Preconditions should be part of the interface rather than part of the implementation,
+but we don't yet have the language facilities to do that.
+Once language support becomes available (e.g., see the [contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf)) we will adopt the standard version of preconditions, postconditions, and assertions.
-* [F.40: Prefer return values to out-parameters](#Rf-T-return)
-* [F.41: Prefer to return tuples to multiple out-parameters](#Rf-T-multi)
-* [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
-* [F.43: Never (directly or indirectly) return a pointer to a local object](#Rf-dangle)
-* [F.44: Return a `T&` when "returning no object" isn't an option](#Rf-return-ref)
-* [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
+##### Note
-Other function rules:
+`Expects()` can also be used to check a condition in the middle of an algorithm.
-* [F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)](#Rf-capture-vs-overload)
-* [F.51: Prefer overloading over default arguments for virtual functions](#Rf-default-arg)
-* [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
-* [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)
+##### Note
-Functions have strong similarities to lambdas and function objects so see also Section ???.
+No, using `unsigned` is not a good way to sidestep the problem of [ensuring that a value is non-negative](#Res-nonnegative).
+##### Enforcement
-
-## F.def: Function definitions
+(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.
-A function definition is a function declaration that also specifies the function's implementation, the function body.
+### I.7: State postconditions
+##### Reason
-
-### F.1: "Package" meaningful operations as carefully named functions
+To detect misunderstandings about the result and possibly catch erroneous implementations.
-**Reason**: Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
-If something is a well-specified action, separate it out from its surrounding code and give it a name.
+##### Example, bad
-**Example, don't**:
+Consider:
- void read_and_print(istream& is) // read and print an int
- {
- int x;
- if (is>>x)
- cout << "the int is " << x << '\n';
- else
- cerr << "no int on input\n";
- }
-
-Almost everything is wrong with `read_and_print`.
-It reads, it writes (to a fixed `ostream`), it write error messages (to a fixed `ostream`), it handles only `int`s.
-There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
-For a tiny example, this looks OK, but if the input operation, the output operation, and the error handling had been more complicated the tangled
-mess could become hard to understand.
+ int area(int height, int width) { return height * width; } // bad
-**Note**: If you write a non-trivial lambda that potentially can be used in more than one place,
-give it a name by assigning it to a (usually non-local) variable.
+Here, we (incautiously) left out the precondition specification, so it is not explicit that height and width must be positive.
+We also left out the postcondition specification, so it is not obvious that the algorithm (`height * width`) is wrong for areas larger than the largest integer.
+Overflow can happen.
+Consider using:
-**Example**:
+ int area(int height, int width)
+ {
+ auto res = height * width;
+ Ensures(res > 0);
+ return res;
+ }
- sort(a, b, [](T x, T y) { return x.valid() && y.valid() && x.value()
-### F.2: A function should perform a single logical operation
+Postconditions are especially important when they relate to something that is not directly reflected in a returned result, such as a state of a data structure used.
-**Reason**: A function that performs a single operation is simpler to understand, test, and reuse.
+##### Example
-**Example**: Consider
+Consider a function that manipulates a `Record`, using a `mutex` to avoid race conditions:
- void read_and_print() // bad
- {
- int x;
- cin >> x;
- // check for errors
- cout << x << "\n";
- }
+ mutex m;
-This is a monolith that is tied to a specific input and will never find a another (different) use. Instead, break functions up into suitable logical parts and parameterize:
+ void manipulate(Record& r) // don't
+ {
+ m.lock();
+ // ... no m.unlock() ...
+ }
- int read(istream& is) // better
- {
- int x;
- is >> x;
- // check for errors
- return x;
- }
+Here, we "forgot" to state that the `mutex` should be released, so we don't know if the failure to ensure release of the `mutex` was a bug or a feature.
+Stating the postcondition would have made it clear:
- void print(ostream& os, int x)
- {
- os << x << "\n";
- }
+ void manipulate(Record& r) // postcondition: m is unlocked upon exit
+ {
+ m.lock();
+ // ... no m.unlock() ...
+ }
-These can now be combined where needed:
+The bug is now obvious (but only to a human reading comments).
- void read_and_print()
- {
- auto x = read(cin);
- print(cout, x);
- }
+Better still, use [RAII](#Rr-raii) to ensure that the postcondition ("the lock must be released") is enforced in code:
-If there was a need, we could further templatize `read()` and `print()` on the data type, the I/O mechanism, etc. Example:
+ void manipulate(Record& r) // best
+ {
+ lock_guard _ {m};
+ // ...
+ }
- auto read = [](auto& input, auto& value) // better
- {
- input >> value;
- // check for errors
- }
+##### Note
- auto print(auto& output, const auto& value)
- {
- output << value << "\n";
- }
+Ideally, postconditions are stated in the interface/declaration so that users can easily see them.
+Only postconditions related to the users can be stated in the interface.
+Postconditions related only to internal state belongs in the definition/implementation.
-**Enforcement**:
+##### Enforcement
-* Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
-* Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
-* Consider functions with 7 or more parameters suspicious.
+(Not enforceable) This is a philosophical guideline that is infeasible to check
+directly in the general case. Domain specific checkers (like lock-holding
+checkers) exist for many toolchains.
+### I.8: Prefer `Ensures()` for expressing postconditions
-
-### F.3: Keep functions short and simple
+##### Reason
-**Reason**: Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
-Functions with complex control structures are more likely to be long and more likely to hide logical errors
+To make it clear that the condition is a postcondition and to enable tool use.
-**Example**: Consider
-
- double simpleFunc(double val, int flag1, int flag2)
- // simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags.
- {
- double intermediate;
- if (flag1 > 0) {
- intermediate = func1(val);
- if (flag2 % 2)
- intermediate = sqrt(intermediate);
- }
- else if (flag1 == -1) {
- intermediate = func1(-val);
- if (flag2 % 2)
- intermediate = sqrt(-intermediate);
- flag1 = -flag1;
- }
- if (abs(flag2) > 10) {
- intermediate = func2(intermediate);
- }
- switch (flag2 / 10) {
- case 1: if (flag1 == -1) return finalize(intermediate, 1.171); break;
- case 2: return finalize(intermediate, 13.1);
- default: ;
- }
- return finalize(intermediate, 0.);
- }
-
-This is too complex (and also pretty long).
-How would you know if all possible alternatives have been correctly handled?
-Yes, it break other rules also.
+##### Example
-We can refactor:
+ void f()
+ {
+ char buffer[MAX];
+ // ...
+ memset(buffer, 0, MAX);
+ Ensures(buffer[0] == 0);
+ }
- double func1_muon(double val, int flag)
- {
- // ???
- }
-
- double funct1_tau(double val, int flag1, int flag2)
- {
- // ???
- }
-
- double simpleFunc(double val, int flag1, int flag2)
- // simpleFunc: takes a value and calculates the expected ASIC output, given the two mode flags.
- {
- if (flag1 > 0)
- return func1_muon(val, flag2);
- if (flag1 == -1)
- return func1_tau(-val, flag1, flag2); // handled by func1_tau: flag1 = -flag1;
- return 0.;
- }
-
-**Note**: "It doesn't fit on a screen" is often a good practical definition of "far too large."
-One-to-five-line functions should be considered normal.
+##### Note
-**Note**: Break large functions up into smaller cohesive and named functions.
-Small simple functions are easily inlined where the cost of a function call is significant.
+Postconditions can be stated in many ways, including comments, `if`-statements, and `assert()`.
+This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and might have the wrong semantics.
-**Enforcement**:
+**Alternative**: Postconditions of the form "this resource must be released" are best expressed by [RAII](#Rr-raii).
-* Flag functions that do not "fit on a screen."
-How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
-* Flag functions that are too complex. How complex is too complex?
-You could use cyclomatic complexity. Try "more that 10 logical path through." Count a simple switch as one path.
+##### Note
+Ideally, that `Ensures` should be part of the interface, but that's not easily done.
+For now, we place it in the definition (function body).
+Once language support becomes available (e.g., see the [contract proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0380r1.pdf)) we will adopt the standard version of preconditions, postconditions, and assertions.
-
-### F.4: If a function may have to be evaluated at compile time, declare it `constexpr`
+##### Enforcement
-**Reason**: `constexpr` is needed to tell the compiler to allow compile-time evaluation.
+(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.
-**Example**: The (in)famous factorial:
+### I.9: If an interface is a template, document its parameters using concepts
- constexpr int fac(int n)
- {
- constexpr int max_exp = 17; // constexpr enables this to be used in Expects
- Expects(0<=x && x
-### F.5: If a function is very small and time critical, declare it `inline`
+ template
+ requires input_iterator && equality_comparable_with, Val>
+ Iter find(Iter first, Iter last, Val v)
+ {
+ // ...
+ }
-**Reason**: Some optimizers are good an inlining without hints from the programmer, but don't rely on it.
-Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
-We are still waiting.
-Specifying `inline` encourages the compiler to do a better job.
+**See also**: [Generic programming](#SS-GP) and [concepts](#SS-concepts).
-**Exception**: Do not put an `inline` function in what is meant to be a stable interface unless you are really sure that it will not change.
-An inline function is part of the ABI.
+##### Enforcement
-**Note**: `constexpr` implies `inline`.
+Warn if any non-variadic template parameter is not constrained by a concept (in its declaration or mentioned in a `requires` clause).
-**Note**: Member functions defined in-class are `inline` by default.
+### I.10: Use exceptions to signal a failure to perform a required task
-**Exception**: Template functions (incl. template member functions) must be in headers and therefore inline.
+##### Reason
-**Enforcement**: Flag `inline` functions that are more than three statements and could have been declared out of line (such as class member functions).
-To fix: Declare the function out of line. [[NM: Certainly possible, but size-based metrics can be very annoying.]]
+It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state.
+This is a major source of errors.
+##### Example
-
-### F.6: If your function may not throw, declare it `noexcept`
+ int printf(const char* ...); // bad: return negative number if output fails
-**Reason**: If an exception is not supposed to be thrown, the program cannot be assumed to cope with the error and should be terminated as soon as possible. Declaring a function `noexcept` helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure.
+ template
+ // good: throw system_error if unable to start the new thread
+ explicit thread(F&& f, Args&&... args);
-**Example**: Put `noexcept` on every function written completely in C or in any other language without exceptions.
-The C++ standard library does that implicitly for all functions in the C standard library.
+##### Note
-**Note**: `constexpr` functions cannot throw, so you don't need to use `noexcept` for those.
+What is an error?
-**Example**: You can use `noexcept` even on functions that can throw:
+An error means that the function cannot achieve its advertised purpose (including establishing postconditions).
+Calling code that ignores an error could lead to wrong results or undefined systems state.
+For example, not being able to connect to a remote server is not by itself an error:
+the server can refuse a connection for all kinds of reasons, so the natural thing is to return a result that the caller should always check.
+However, if failing to make a connection is considered an error, then a failure should throw an exception.
- vector collect(istream& is) noexcept
- {
- vector res;
- for(string s; is>>s; )
- res.push_back(s);
- return res;
- }
+##### Exception
-If `collect()` runs out of memory, the program crashes.
-Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do;
-`terminate()` may generate suitable error log information (but after memory runs out it is hard to do anything clever).
+Many traditional interface functions (e.g., UNIX signal handlers) use error codes (e.g., `errno`) to report what are really status codes, rather than errors. You don't have a good alternative to using such, so calling these does not violate the rule.
-**Note**: In most programs, most functions can throw
-(e.g., because they use `new`, call functions that do, or use library functions that reports failure by throwing),
-so don't just springle `noexcept` all over the place.
-`noexcept` is most useful for frequently used, low-level functions.
+##### Alternative
-**Note**: Destructors, `swap` functions, move operations, and default constructors should never throw.
+If you can't use exceptions (e.g., because your code is full of old-style raw-pointer use or because there are hard-real-time constraints), consider using a style that returns a pair of values:
+ int val;
+ int error_code;
+ tie(val, error_code) = do_something();
+ if (error_code) {
+ // ... handle the error or exit ...
+ }
+ // ... use val ...
-**Enforcement**:
+This style unfortunately leads to uninitialized variables.
+Since C++17 the "structured bindings" feature can be used to initialize variables directly from the return value:
-* Flag functions that are not `noexcept`, yet cannot throw
-* Flag throwing `swap`, `move`, destructors, and default constructors.
+ auto [val, error_code] = do_something();
+ if (error_code) {
+ // ... handle the error or exit ...
+ }
+ // ... use val ...
+##### Note
-
-### F.7: For general use, take `T*` arguments rather than a smart pointers
+We don't consider "performance" a valid reason not to use exceptions.
-**Reason**: Passing a smart pointer transfers or shares ownership.
-Passing by smart pointer restricts the use of a function to callers that use smart pointers.
-Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
+* Often, explicit error checking and handling consume as much time and space as exception handling.
+* Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
+* A good rule for performance critical code is to move checking outside the [critical](#Rper-critical) part of the code.
+* In the longer term, more regular code gets better optimized.
+* Always carefully [measure](#Rper-measure) before making performance claims.
-**Example**:
+**See also**: [I.5](#Ri-pre) and [I.7](#Ri-post) for reporting precondition and postcondition violations.
- void f(int*); // accepts any int*
- void g(unique_ptr); // can only accept ints for which you want to transfer ownership
- void g(shared_ptr); // can only accept ints for which you are willing to share ownership
+##### Enforcement
-**Note**: We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.
+* (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
+* Look for `errno`.
-**See also**: Discussion of [smart pointer use](#Rr-summary-smartptrs).
+### I.11: Never transfer ownership by a raw pointer (`T*`) or reference (`T&`)
-**Enforcement**: Flag smart pointer arguments.
+##### Reason
+If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
-
-### F.8: Prefer pure functions
+##### Example
+Consider:
-**Reason**: Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
+ X* compute(args) // don't
+ {
+ X* res = new X{};
+ // ...
+ return res;
+ }
-**Example**:
+Who deletes the returned `X`? The problem would be harder to spot if `compute` returned a reference.
+Consider returning the result by value (use move semantics if the result is large):
- template
- auto square(T t) { return t*t; }
-
-**Note**: `constexpr` functions are pure.
-
-**Enforcement**: not possible.
+ vector compute(args) // good
+ {
+ vector res(10000);
+ // ...
+ return res;
+ }
+**Alternative**: [Pass ownership](#Rr-smartptrparam) using a "smart pointer", such as `unique_ptr` (for exclusive ownership) and `shared_ptr` (for shared ownership).
+However, that is less elegant and often less efficient than returning the object itself,
+so use smart pointers only if reference semantics are needed.
-
-## F.call: Argument passing
+**Alternative**: Sometimes older code can't be modified because of ABI compatibility requirements or lack of resources.
+In that case, mark owning pointers using `owner` from the [guidelines support library](#gsl-guidelines-support-library):
-There are a variety of ways to pass arguments to a function and to return values.
+ owner compute(args) // It is now clear that ownership is transferred
+ {
+ owner res = new X{};
+ // ...
+ return res;
+ }
+This tells analysis tools that `res` is an owner.
+That is, its value must be `delete`d or transferred to another owner, as is done here by the `return`.
-
-### Rule F.15: Prefer simple and conventional ways of passing information
+`owner` is used similarly in the implementation of resource handles.
-**Reason**: Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
-If you really feel the need for an optimization beyond the common techniques, measure to ensure that it really is an improvement,
-and document/comment because the improvement may not be portable.
+##### Note
-
+Every object passed as a raw pointer (or iterator) is assumed to be owned by the
+caller, so that its lifetime is handled by the caller. Viewed another way:
+ownership transferring APIs are relatively rare compared to pointer-passing APIs,
+so the default is "no ownership transfer."
-**For an "output-only" value:** Prefer return values to output parameters.
-This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
-If you have multiple values to return, [use a tuple](#Rf-T-multi) or similar multi-member type.
+**See also**: [Argument passing](#Rf-conventional), [use of smart pointer arguments](#Rr-smartptrparam), and [value return](#Rf-value-return).
-**Example**:
+##### Enforcement
- vector find_all(const vector&, int x); // return pointers to elements with the value x
-
-**Example, bad**:
+* (Simple) Warn on `delete` of a raw pointer that is not an `owner`. Suggest use of standard-library resource handle or use of `owner`.
+* (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 an `owner` return value is assigned to a raw pointer or non-`owner` reference.
- void find_all(const vector&, vector& out, int x); // place pointers to elements with value x in out
+### I.12: Declare a pointer that must not be null as `not_null`
-**Exceptions**:
+##### Reason
-* For non-value types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
-* If a type is expensive to move (e.g., `array`), consider allocating it on the free store and return a handle (e.g., `unique_ptr`), or passing it in a non-`const` reference to a target object to fill (to be used as an out-parameter).
-* In the special case of allowing a caller to reuse an object that carries capacity (e.g., `std::string`, `std::vector`) across multiple calls to the function in an inner loop, treat it as an in/out parameter instead and pass by `&`. This one use of the more generally named "caller-allocated out" pattern.
+To help avoid dereferencing `nullptr` errors.
+To improve performance by avoiding redundant checks for `nullptr`.
-**For an "in-out" parameter:** Pass by non-`const` reference. This makes it clear to callers that the object is assumed to be modified.
+##### Example
-**For an "input-only" value:** If the object is cheap to copy, pass by value.
-Otherwise, pass by `const&`. It is useful to know that a function does not mutate an argument, and both allow initialization by rvalues.
-What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
-In particular, an object passed by value does not require an extra reference to access from the function.
+ int length(const char* p); // it is not clear whether length(nullptr) is valid
-
+ length(nullptr); // OK?
-For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
+ int length(not_null p); // better: we can assume that p cannot be nullptr
-* If the function is going to unconditionally move from the argument, take it by `&&`.
-* If the function is going to keep a copy of the argument, in addition to passing by `const&` add an overload that passes the parameter by `&&` and in the body `std::move`s it to its destination. (See [F.25](#Rf-pass-ref-move).)
-* In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. (See [F.24](#Rf-pass-ref-ref).)
+ int length(const char* p); // we must assume that p can be nullptr
-**Example**:
+By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.
- int multiply(int, int); // just input ints, pass by value
-
- string& concatenate(string&, const string& suffix); // suffix is input-only but not as cheap as an int, pass by const&
-
- void sink(unique_ptr); // input only, and consumes the widget
-
-Avoid "esoteric techniques" such as:
+##### Note
-* Passing arguments as `T&&` "for efficiency". Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.25](#Rf-pass-ref-move).)
-* Returning `const T&` from assignments and similar operations.
+`not_null` is defined in the [guidelines support library](#gsl-guidelines-support-library).
-**Example**: Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`.
+##### Note
- Matrix operator+(const Matrix& a, const Matrix& b)
- {
- Matrix res;
- // ... fill res with the sum ...
- return res;
- }
+The assumption that the pointer to `char` pointed to a C-style string (a zero-terminated string of characters) was still implicit, and a potential source of confusion and errors. Use `czstring` in preference to `const char*`.
- Matrix x = m1+m2; // move constructor
+ // we can assume that p cannot be nullptr
+ // we can assume that p points to a zero-terminated array of characters
+ int length(not_null p);
- y = m3+m3; // move assignment
+Note: `length()` is, of course, `std::strlen()` in disguise.
-**Note**: The (optional) return value optimization doesn't handle the assignment case.
+##### Enforcement
-**See also**: [implicit arguments](#Ri-explicit).
+* (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`.
-**Enforcement**: This is a philosophical guideline that is infeasible to check directly and completely.
-However, many of the the detailed rules (F.16-F.45) can be checked,
-such as passing a `const int&`, returning an `array` by value, and returning a pointer to fre store alloced by the function.
+### I.13: Do not pass an array as a single pointer
+##### Reason
-
-### F.16: Use `T*` or `owner` to designate a single object
+ (pointer, size)-style interfaces are error-prone. Also, a plain pointer (to array) must rely on some convention to allow the callee to determine the size.
-**Reason**: In traditional C and C++ code, "Plain `T*` is used for many weakly-related purposes, such as
+##### Example
-* Identify a (single) object (not to be deleted by this function)
-* Point to an object allocated on the free store (and delete it later)
-* Hold the `nullptr`
-* Identify a C-style string (zero-terminated array of characters)
-* Identify an array with a length specified separately
-* Identify a location in an array
+Consider:
-Confusion about what meaning a `T*` is the source of many serious errors, so using separate names for pointers of these separate uses makes code clearer.
-For debugging, `owner` and `not_null` can be instrumented to check.
-For example, `not_null` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
+ void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)
-**Example**: Consider
+What if there are fewer than `n` elements in the array pointed to by `q`? Then, we overwrite some probably unrelated memory.
+What if there are fewer than `n` elements in the array pointed to by `p`? Then, we read some probably unrelated memory.
+Either is undefined behavior and a potentially very nasty bug.
- int length(Record* p);
+##### Alternative
-When I call `length(r)` should I test for `r==nullptr` first? Should the implementation of `length()` test for `p==nullptr`?
+Consider using explicit spans:
- int length(not_null p); // it is the caller's job to make sure p!=nullptr
+ void copy(span r, span r2); // copy r to r2
- int length(Record* p); // the implementor of length() must assume that p==nullptr is possible
+##### Example, bad
-**Note**: A `not_null` is assumed not to be the `nullptr`; a `T*` may be the `nullptr`; both can be represented in memory as a `T*` (so no run-time overhead is implied).
+Consider:
-**Note**: `owner` represents ownership.
+ void draw(Shape* p, int n); // poor interface; poor code
+ Circle arr[10];
+ // ...
+ draw(arr, 10);
-**Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., unique_ptr<`T`>) pointes to a single element.
+Passing `10` as the `n` argument might be a mistake: the most common convention is to assume `[0:n)` but that is nowhere stated. Worse is that the call of `draw()` compiled at all: there was an implicit conversion from array to pointer (array decay) and then another implicit conversion from `Circle` to `Shape`. There is no way that `draw()` can safely iterate through that array: it has no way of knowing the size of the elements.
-**See also**: [Support library](#S-gsl).
+**Alternative**: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:
-**Enforcement**:
+ void draw2(span);
+ Circle arr[10];
+ // ...
+ draw2(span(arr)); // deduce the number of elements
+ draw2(arr); // deduce the element type and array size
-* (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
+ void draw3(span);
+ draw3(arr); // error: cannot convert Circle[10] to span
+This `draw2()` passes the same amount of information to `draw()`, but makes the fact that it is supposed to be a range of `Circle`s explicit. See ???.
-
-### F.17: Use a `not_null` to indicate that "null" is not a valid value
+##### Exception
-**Reason**: Clarity. Making it clear that a test for null isn't needed.
+Use `zstring` and `czstring` to represent C-style, zero-terminated strings.
+But when doing so, use `std::string_view` or `span` from the [GSL](#gsl-guidelines-support-library) to prevent range errors.
-**Example**:
+##### Enforcement
- not_null check(T* p) { if (p) return not_null{p}; throw Unexpected_nullptr{}; }
+* (Simple) ((Bounds)) Warn for any expression that would rely on implicit conversion of an array type to a pointer type. Allow exception for zstring/czstring pointer types.
+* (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. Allow exception for zstring/czstring pointer types.
- void computer(not_null> p)
- {
- if (0I.22: Avoid complex initialization of global objects
-**Note**: `not_null` is not just for built-in pointers. It works for `array_view`, `string_view`, `unique_ptr`, `shared_ptr`, and other pointer-like types.
+##### Reason
-**Enforcement**:
+Complex initialization can lead to undefined order of execution.
-* (Simple) Warn if a raw pointer is dereferenced without being tested against `nullptr` (or equivalent) within a function, suggest it is declared `not_null` instead.
-* (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
-* (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
+##### Example
+ // file1.c
-
-### F.18: Use an `array_view` or an `array_view_p` to designate a half-open sequence
+ extern const X x;
-**Reason**: Informal/non-explicit ranges are a source of errors
+ const Y y = f(x); // read x; write y
-**Example**:
+ // file2.c
- X* find(array_view r, const X& v) // find v in r
+ extern const Y y;
- vector vec;
- // ...
- auto p = find({vec.begin(),vec.end()},X{}); // find X{} in vec
+ const X x = g(y); // read y; write x
-**Note**: Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure. In particular, given a pair of arguments `(p,n)` designating an array [`p`:`p+n`), it is in general impossible to know if there really are n elements to access following `*p`. `array_view` and `array_view_p` are simple helper classes designating a [p:q) range and a range starting with p and ending with the first element for which a predicate is true, respectively.
+Since `x` and `y` are in different translation units the order of calls to `f()` and `g()` is undefined;
+one will access an uninitialized `const`.
+This shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global *variables*.
-**Note**: an `array_view` object does not own its elements and is so small that it can be passed by value.
+##### Note
-**Note**: Passing an `array_view` object as an argument is exactly as efficient as passing a pair of pointer arguments or passing a pointer and an integer count.
+Order of initialization problems become particularly difficult to handle in concurrent code.
+It is usually best to avoid global (namespace scope) objects altogether.
-**See also**: [Support library](#S-gsl).
+##### Enforcement
-**Enforcement**: (Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use `array_view` instead.
+* 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
-
-### F.19: Use a `zstring` or a `not_null` to designate a C-style string
+##### Reason
-**Reason**: C-style strings are ubiquitous.
-They are defined by convention: zero-terminated arrays of characters.
-Functions are inconsistent in their use of `nullptr` and we must be more explicit.
+Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
-**Example**: Consider
+##### Discussion
- int length(const char* p);
+The two most common reasons why functions have too many parameters are:
-When I call `length(s)` should I test for `s==nullptr` first? Should the implementation of `length()` test for `p==nullptr`?
+1. *Missing an abstraction.*
+ There is an abstraction missing, so that a compound value is being
+ passed as individual elements instead of as a single object that enforces an invariant.
+ This not only expands the parameter list, but it leads to errors because the component values
+ are no longer protected by an enforced invariant.
- int length(zstring p); // it is the caller's job to make sure p!=nullptr
+2. *Violating "one function, one responsibility."*
+ The function is trying to do more than one job and should probably be refactored.
- int length(not_null p); // the implementor of length() must assume that p==nullptr is possible
+##### Example
-**Note**: `zstring` do not represent ownership.
+The standard-library `merge()` is at the limit of what we can comfortably handle:
-**See also**: [Support library](#S-gsl).
+ template
+ OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
+ InputIterator2 first2, InputIterator2 last2,
+ OutputIterator result, Compare comp);
+Note that this is because of problem 1 above -- missing abstraction. Instead of passing a range (abstraction), STL passed iterator pairs (unencapsulated component values).
-
-### F.20: Use a `const T&` parameter for a large object
+Here, we have four template arguments and six function arguments.
+To simplify the most frequent and simplest uses, the comparison argument can be defaulted to `<`:
-**Reason**: Copying large objects can be expensive. A `const T&` is always cheap and protects the caller from unintended modification.
+ template
+ OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
+ InputIterator2 first2, InputIterator2 last2,
+ OutputIterator result);
-**Example**:
+This doesn't reduce the total complexity, but it reduces the surface complexity presented to many users.
+To really reduce the number of arguments, we need to bundle the arguments into higher-level abstractions:
- void fct(const string& s); // OK: pass by const reference; always checp
+ template
+ OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);
- void fct2(string s); // bad: potentially expensive
+Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.
-**Exception**: Sinks (that is, a function that eventually destroys an object or passes it along to another sink), may benefit ???
+Alternatively, we could use a standard library concept to define the notion of three types that must be usable for merging:
-**Note**: A reference may be assumed to refer to a valid object (language rule).
-There in no (legitimate) "null reference."
-If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
+ template
+ requires mergeable
+ Out merge(In1 r1, In2 r2, Out result);
-**Enforcement**:
+##### Example
-* (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `4*sizeof(int)`.
-Suggest using a `const` reference instead.
+The safety Profiles recommend replacing
+ void f(int* some_ints, int some_ints_length); // BAD: C style, unsafe
-
-### F.21: Use a `T` parameter for a small object
+with
-**Reason**: Nothing beats the simplicity and safety of copying.
-For small objects (up to two or three words) is is also faster than alternatives.
+ void f(gsl::span some_ints); // GOOD: safe, bounds-checked
-**Example**:
+Here, using an abstraction has safety and robustness benefits, and naturally also reduces the number of parameters.
- void fct(int x); // OK: Unbeatable
+##### Note
- void fct(const int& x); // bad: overhead on access in fct2()
+How many parameters are too many? Try to use fewer than four (4) parameters.
+There are functions that are best expressed with four individual parameters, but not many.
- void fct(int& x); // OK, but means something else; use only for an "out parameter"
+**Alternative**: Use better abstraction: Group arguments into meaningful objects and pass the objects (by value or by reference).
-**Enforcement**:
+**Alternative**: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.
-* (Simple) ((Foundation)) Warn when a `const` parameter being passed by reference has a size less than `3*sizeof(int)`. Suggest passing by value instead.
+##### Enforcement
+* Warn when a function 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.
-
-### F.22: Use a `T&` for an in-out-parameter
+### I.24: Avoid adjacent parameters that can be invoked by the same arguments in either order with different meaning
-**Reason**: A called function can write to a non-`const` reference argument, so assume that it does.
+##### Reason
-**Example**:
+Adjacent arguments of the same type are easily swapped by mistake.
- void update(Record& r); // assume that update writes to r
-
-**Note**: A `T&` argument can pass information into a function as well as well as out of it.
-Thus `T&` could be and in-out-parameter. That can in itself be a problem and a source of errors:
+##### Example, bad
- void f(string& s)
- {
- s = "New York"; // non-obvious error
- }
-
- string g()
- {
- string buffer = ".................................";
- f(buffer);
- // ...
- }
-
-Here, the writer of `g()` is supplying a buffer for `f()` to fill,
-but `f()` simply replaces it (at a somewhat higher cost than a simple copy of the characters).
-If the writer of `g()` makes an assumption about the size of `buffer` a bad logic error can happen.
+Consider:
-**Enforcement**:
+ void copy_n(T* p, T* q, int n); // copy from [p:p + n) to [q:q + n)
-* (Moderate) ((Foundation)) Warn about functions with non-`const` reference arguments that do *not* write to them.
-* Flag functions that take a `T&` and replace the `T` referred to, rather what the contents of that `T`
+This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
+Use `const` for the "from" argument:
-
-### F.23: Use `T&` for an out-parameter that is expensive to move (only)
+ void copy_n(const T* p, T* q, int n); // copy from [p:p + n) to [q:q + n)
-**Reason**: A return value is harder to miss and harder to misuse than a `T&` (an in-out parameter); [see also](#Rf-return); [see also](#Rf-T-multi).
+##### Exception
-**Example**:
+If the order of the parameters is not important, there is no problem:
- struct Package {
- char header[16];
- char load[2024-16];
- };
-
- Package fill(); // Bad: large return value
- void fill(Package&); // OK
-
- int val(); // OK
- val(int&); // Bad: Is val reading its argument
+ int max(int a, int b);
-**Enforcement**: Hard to choose a cutover value for the size of the value returned.
+##### Alternative
+Don't pass arrays as pointers, pass an object representing a range (e.g., a `span`):
-
-### F.24: Use a `TP&&` parameter when forwarding (only)
+ void copy_n(span p, span q); // copy from p to q
-**Reason**: When `TP` is a template type parameter, `TP&&` is a forwarding reference -- it both *ignores* and *preserves* const-ness and rvalue-ness. Therefore any code that uses a `T&&` is implicitly declaring that it itself doesn't care about the variable's const-ness and rvalue-ness (because it is ignored), but that intends to pass the value onward to other code that does care about const-ness and rvalue-ness (because it is preserved). When used as a parameter `TP&&` is safe because any temporary objects passed from the caller will live for the duration of the function call. A parameter of type `TP&&` should essentially always be passed onward via `std::forward` in the body of the function.
+##### Alternative
-**Example**:
+Define a `struct` as the parameter type and name the fields for those parameters accordingly:
- template
- inline auto invoke(F&& f, Args&&... args) {
- return forward(f)(forward(args)...);
- }
+ struct SystemParams {
+ string config_file;
+ string output_path;
+ seconds timeout;
+ };
+ void initialize(SystemParams p);
-**Enforcement**: Flag a function that takes a `TP&&` parameter (where `TP` is a template type parameter name) and uses it without `std::forward`.
+This tends to make invocations of this clear to future readers, as the parameters
+are often filled in by name at the call site.
+##### Note
-
-### F.25: Use a `T&&` parameter together with `move` for rare optimization opportunities
+Only the interface's designer can adequately address the source of violations of this guideline.
-**Reason**: Moving from an object leaves an object in its moved-from state behind.
-In general, moved-from objects are dangerous. The only guaranteed operation is destruction (more generally, member functions without preconditions).
-The standard library additionally requires that a moved-from object can be assigned to.
-If you have performance justification to optimize for rvalues, overload on `&&` and then `move` from the parameter ([example of such overloading](#)).
+##### Enforcement strategy
-**Example**:
+(Simple) Warn if two consecutive parameters share the same type
- void somefct(string&&);
-
- void user()
- {
- string s = "this is going to be fun!";
- // ...
- somefct(std::move(s)); // we don't need s any more, give it to somefct()
- //
- cout << s << '\n'; // Oops! What happens here?
- }
+We are still looking for a less-simple enforcement.
-**Enforcement**:
+### I.25: Prefer empty abstract classes as interfaces to class hierarchies
-* Flag all `X&&` parameters (where `X` is not a template type parameter name) and uses it without `std::move`.
-* Flag access to moved-from objects
+##### Reason
+Abstract classes that are empty (have no non-static member data) are more likely to be stable than base classes with state.
-
-### F.26: Use a `unique_ptr` to transfer ownership where a pointer is needed
+##### Example, bad
-**Reason**: Using `unique_ptr` is the cheapest way to pass a pointer safely.
+You just knew that `Shape` would turn up somewhere :-)
-**Example**:
+ class Shape { // bad: interface class loaded with data
+ public:
+ Point center() const { return c; }
+ virtual void draw() const;
+ virtual void rotate(int);
+ // ...
+ private:
+ Point c;
+ vector outline;
+ Color col;
+ };
- unique_ptr get_shape(istream& is) // assemble shape from input stream
- {
- auto kind = read_header(is); // read header and identify the next shape on input
- switch (kind) {
- case kCicle:
- return make_unique(is);
- case kTriangle:
- return make_unique(is);
- // ...
- }
+This will force every derived class to compute a center -- even if that's non-trivial and the center is never used. Similarly, not every `Shape` has a `Color`, and many `Shape`s are best represented without an outline defined as a sequence of `Point`s. Using an abstract class is better:
-**Note**: You need to pass a pointer rather than an object if what you are transferring is an object from a class hierarchy that is to be used through an interface (base class).
+ class Shape { // better: Shape is a pure interface
+ public:
+ virtual Point center() const = 0; // pure virtual functions
+ virtual void draw() const = 0;
+ virtual void rotate(int) = 0;
+ // ...
+ // ... no data members ...
+ // ...
+ virtual ~Shape() = default;
+ };
-**Enforcement**: (Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either `unique_ptr` or `shared_ptr` instead.
+##### Enforcement
+(Simple) Warn if a pointer/reference to a class `C` is assigned to a pointer/reference to a base of `C` and the base class contains data members.
-
-### F.27: Use a `shared_ptr` to share ownership
+### I.26: If you want a cross-compiler ABI, use a C-style subset
-**Reason**: Using `std::shared_ptr` is the standard way to represent shared ownership. That is, the last owner deletes the object.
+##### Reason
-**Example**:
+Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
- shared_ptr im { read_image(somewhere); };
-
- std::thread t0 {shade,args0,top_left,im};
- std::thread t1 {shade,args1,top_right,im};
- std::thread t2 {shade,args2,bottom_left,im};
- std::thread t3 {shade,args3,bottom_right,im};
-
- // detach treads
- // last thread to finish deletes the image
+##### Exception
+Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
-**Note**: Prefer a `unique_ptr` over a `shared_ptr` if there is never more than one owner at a time.
-`shared_ptr` is for shared ownership.
+##### Note
-**Alternative**: Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completd.
+If you use a single compiler, you can use full C++ in interfaces. That might require recompilation after an upgrade to a new compiler version.
-**Enforcement**: (Not enforceable) This is a too complex pattern to reliably detect.
+##### Enforcement
+(Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
-
-### F.40: Prefer return values to out-parameters
+### I.27: For stable library ABI, consider the Pimpl idiom
-**Reason**: It's self-documenting. A `&` parameter could be either in/out or out-only.
+##### Reason
-**Example**:
+Because private data members participate in class layout and private member functions participate in overload resolution, changes to those
+implementation details require recompilation of all users of a class that uses them. A non-polymorphic interface class holding a pointer to
+implementation (Pimpl) can isolate the users of a class from changes in its implementation at the cost of an indirection.
- void incr(int&);
- int incr();
-
- int i = 0;
- incr(i);
- i = incr(i);
+##### Example
-**Enforcement**: Flag non-const reference parameters that are not read before being written to and are a type that could be cheaply returned.
+interface (widget.h)
+ class widget {
+ class impl;
+ std::unique_ptr pimpl;
+ public:
+ void draw(); // public API that will be forwarded to the implementation
+ widget(int); // defined in the implementation file
+ ~widget(); // defined in the implementation file, where impl is a complete type
+ widget(widget&&) noexcept; // defined in the implementation file
+ widget(const widget&) = delete;
+ widget& operator=(widget&&) noexcept; // defined in the implementation file
+ widget& operator=(const widget&) = delete;
+ };
-
-### F.41: Prefer to return tuples to multiple out-parameters
-**Reason**: A return value is self-documenting as an "output-only" value.
-And yes, C++ does have multiple return values, by convention of using a `tuple`, with the extra convenience of `tie` at the call site.
+implementation (widget.cpp)
-**Example**:
+ class widget::impl {
+ int n; // private data
+ public:
+ void draw(const widget& w) { /* ... */ }
+ impl(int n) : n(n) {}
+ };
+ void widget::draw() { pimpl->draw(*this); }
+ widget::widget(int n) : pimpl{std::make_unique(n)} {}
+ widget::widget(widget&&) noexcept = default;
+ widget::~widget() = default;
+ widget& widget::operator=(widget&&) noexcept = default;
- int f( const string& input, /*output only*/ string& output_data ) { // BAD: output-only parameter documented in a comment
- // ...
- output_data = something();
- return status;
- }
+##### Notes
- tuple f( const string& input ) { // GOOD: self-documenting
- // ...
- return make_tuple(something(), status);
- }
+See [GOTW #100](https://herbsutter.com/gotw/_100/) and [cppreference](http://en.cppreference.com/w/cpp/language/pimpl) for the trade-offs and additional implementation details associated with this idiom.
-In fact, C++98's standard library already used this convenient feature, because a `pair` is like a two-element `tuple`.
-For example, given a `set myset`, consider:
+##### Enforcement
- // C++98
- result = myset.insert( “Hello” );
- if (result.second) do_something_with( result.first ); // workaround
-
-With C++11 we can write this, putting the results directly in existing local variables:
+(Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
- Sometype iter; // default initialize if we haven't already
- Someothertype success; // used these variables for some other purpose
+### I.30: Encapsulate rule violations
- tie( iter, success ) = myset.insert( “Hello” ); // normal return value
- if (success) do_something_with( iter );
+##### Reason
-**Exception**: For types like `string` and `vector` that carry additional capacity, it can sometimes be useful to treat it as in/out instead by using the "caller-allocated out" pattern, which is to pass an output-only object by reference to non-`const` so that when the callee writes to it the object can reuse any capacity or other resources that it already contains. This technique can dramatically reduce the number of allocations in a loop that repeatedly calls other functions to get string values, by using a single string object for the entire loop.
+To keep code simple and safe.
+Sometimes, ugly, unsafe, or error-prone techniques are necessary for logical or performance reasons.
+If so, keep them local, rather than "infecting" interfaces so that larger groups of programmers have to be aware of the
+subtleties.
+Implementation complexity should, if at all possible, not leak through interfaces into user code.
-**Note**: In some cases it may be useful to return a specific, user-defined `Value_or_error` type along the lines of `variant`,
-rather than using the generic `tuple`.
+##### Example
-**Enforcement**:
+Consider a program that, depending on some form of input (e.g., arguments to `main`), should consume input
+from a file, from the command line, or from standard input.
+We might write
- * Output parameters should be replaced by return values.
- An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
+ bool owned;
+ owner inp;
+ switch (source) {
+ case std_in: owned = false; inp = &cin; break;
+ case command_line: owned = true; inp = new istringstream{argv[2]}; break;
+ case file: owned = true; inp = new ifstream{argv[2]}; break;
+ }
+ istream& in = *inp;
+This violated the rule [against uninitialized variables](#Res-always),
+the rule against [ignoring ownership](#Ri-raw),
+and the rule [against magic constants](#Res-magic).
+In particular, someone has to remember to somewhere write
-
-### F.42: Return a `T*` to indicate a position (only)
+ if (owned) delete inp;
-**Reason**: That's what pointers are good for.
-Returning a `T*` to transfer ownership is a misuse.
+We could handle this particular example by using `unique_ptr` with a special deleter that does nothing for `cin`,
+but that's complicated for novices (who can easily encounter this problem) and the example is an example of a more general
+problem where a property that we would like to consider static (here, ownership) needs infrequently be addressed
+at run time.
+The common, most frequent, and safest examples can be handled statically, so we don't want to add cost and complexity to those.
+But we must also cope with the uncommon, less-safe, and necessarily more expensive cases.
+Such examples are discussed in [[Str15]](http://www.stroustrup.com/resource-model.pdf).
-**Note**: Do not return a pointer to something that is not in the caller's scope.
+So, we write a class
-**Example**:
+ class Istream { [[gsl::suppress("lifetime")]]
+ public:
+ enum Opt { from_line = 1 };
+ Istream() { }
+ Istream(czstring p) : owned{true}, inp{new ifstream{p}} {} // read from file
+ Istream(czstring p, Opt) : owned{true}, inp{new istringstream{p}} {} // read from command line
+ ~Istream() { if (owned) delete inp; }
+ operator istream&() { return *inp; }
+ private:
+ bool owned = false;
+ istream* inp = &cin;
+ };
- Node* find(Node* t, const string& s) // find s in a binary tree of Nodes
- {
- if (t == nullptr || t->name == s) return t;
- if (auto p = find(t->left,s)) return p;
- if (auto p = find(t->right,s)) return p;
- return nullptr;
- }
+Now, the dynamic nature of `istream` ownership has been encapsulated.
+Presumably, a bit of checking for potential errors would be added in real code.
-If it isn't the `nullptr`, the pointer returned by `find` indicates a `Node` holding `s`.
-Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.
+##### Enforcement
-**Note**: Positions can also be transferred by iterators, indices, and references.
+* Hard, it is hard to decide what rule-breaking code is essential
+* Flag rule suppression that enable rule-violations to cross interfaces
-**Example, bad**:
+# F: Functions
- int* f()
- {
- int x = 7;
- // ...
- return &x; // Bad: returns pointer to object that is about to be destroyed
- }
+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.
-This applies to references as well:
+It should be possible to name a function meaningfully, to specify the requirements of its argument, and clearly state the relationship between the arguments and the result. An implementation is not a specification. Try to think about what a function does as well as about how it does it.
+Functions are the most critical part in most interfaces, so see the interface rules.
- int& f()
- {
- int x = 7;
- // ...
- return x; // Bad: returns reference to object that is about to be destroyed
- }
+Function rule summary:
-**See also**: [discussion of dangling pointer prevention](#???).
+Function definition rules:
-**Enforcement**: A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.
+* [F.1: "Package" meaningful operations as carefully named functions](#Rf-package)
+* [F.2: A function should perform a single logical operation](#Rf-logical)
+* [F.3: Keep functions short and simple](#Rf-single)
+* [F.4: If a function might have to be evaluated at compile time, declare it `constexpr`](#Rf-constexpr)
+* [F.5: If a function is very small and time-critical, declare it inline](#Rf-inline)
+* [F.6: If your function must not throw, declare it `noexcept`](#Rf-noexcept)
+* [F.7: For general use, take `T*` or `T&` arguments rather than smart pointers](#Rf-smart)
+* [F.8: Prefer pure functions](#Rf-pure)
+* [F.9: Unused parameters should be unnamed](#Rf-unused)
+* [F.10: If an operation can be reused, give it a name](#Rf-name)
+* [F.11: Use an unnamed lambda if you need a simple function object in one place only](#Rf-lambda)
-* Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
-* Static analysis can catch most (all?) common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)
-
-
-
-### F.43: Never (directly or indirectly) return a pointer to a local object
-
-**Reason**: To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
-
-**Example**, bad: After the return from a function its local objects no longer exist:
-
- int* f()
- {
- int fx = 9;
- return &fx; // BAD
- }
-
- void g(int* p) // looks innocent enough
- {
- int gx;
- cout << "*p == " << *p << '\n';
- *p = 999;
- cout << "gx == " << gx << '\n';
- }
-
- void h()
- {
- int* p = f();
- int z = *p; // read from abandoned stack frame (bad)
- g(p); // pass pointer to abandoned stack frame to function (bad)
-
- }
-
-Here on one popular implementation I got the output
-
- *p == 9
- cx == 999
-
-I expected that because the call of `g()` reuses the stack space abandoned by the call of `f()` so `*p` refers to the space now occupied by `gx`.
+Parameter passing expression rules:
-Imagine what would happen if `fx` and `gx` were of different types.
-Imagine what would happen if `fx` or `gx` was a type with an invariant.
-Imagine what would happen if more that dangling pointer was passed around among a larger set of functions.
-Imagine what a cracker could do with that dangling pointer.
+* [F.15: Prefer simple and conventional ways of passing information](#Rf-conventional)
+* [F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`](#Rf-in)
+* [F.17: For "in-out" parameters, pass by reference to non-`const`](#Rf-inout)
+* [F.18: For "will-move-from" parameters, pass by `X&&` and `std::move` the parameter](#Rf-consume)
+* [F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter](#Rf-forward)
+* [F.20: For "out" output values, prefer return values to output parameters](#Rf-out)
+* [F.21: To return multiple "out" values, prefer returning a struct](#Rf-out-multi)
+* [F.60: Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
+
+Parameter passing semantic rules:
+
+* [F.22: Use `T*` or `owner` to designate a single object](#Rf-ptr)
+* [F.23: Use a `not_null` to indicate that "null" is not a valid value](#Rf-nullptr)
+* [F.24: Use a `span` or a `span_p` to designate a half-open sequence](#Rf-range)
+* [F.25: Use a `zstring` or a `not_null` to designate a C-style string](#Rf-zstring)
+* [F.26: Use a `unique_ptr` to transfer ownership where a pointer is needed](#Rf-unique_ptr)
+* [F.27: Use a `shared_ptr` to share ownership](#Rf-shared_ptr)
-Fortunately, most (all?) modern compilers catch and warn against this simple case.
+Value return semantic rules:
-**Note**: you can construct similar examples using references.
+* [F.42: Return a `T*` to indicate a position (only)](#Rf-return-ptr)
+* [F.43: Never (directly or indirectly) return a pointer or a reference to a local object](#Rf-dangle)
+* [F.44: Return a `T&` when copy is undesirable and "returning no object" isn't needed](#Rf-return-ref)
+* [F.45: Don't return a `T&&`](#Rf-return-ref-ref)
+* [F.46: `int` is the return type for `main()`](#Rf-main)
+* [F.47: Return `T&` from assignment operators](#Rf-assignment-op)
+* [F.48: Don't return `std::move(local)`](#Rf-return-move-local)
+* [F.49: Don't return `const T`](#Rf-return-const)
-**Note**: This applies only to non-`static` local variables.
-All `static` variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.
+Other function rules:
-**Example**, bad: Not all examples of leaking a pointer to a local variable are that obvious:
+* [F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)](#Rf-capture-vs-overload)
+* [F.51: Where there is a choice, prefer default arguments over overloading](#Rf-default-args)
+* [F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms](#Rf-reference-capture)
+* [F.53: Avoid capturing by reference in lambdas that will be used non-locally, including returned, stored on the heap, or passed to another thread](#Rf-value-capture)
+* [F.54: When writing a lambda that captures `this` or any class data member, don't use `[=]` default capture](#Rf-this-capture)
+* [F.55: Don't use `va_arg` arguments](#F-varargs)
+* [F.56: Avoid unnecessary condition nesting](#F-nesting)
- int* glob; // global variables are bad in so many ways
+Functions have strong similarities to lambdas and function objects.
- template
- void steal(T x)
- {
- glob = x(); // BAD
- }
+**See also**: [C.lambdas: Function objects and lambdas](#SS-lambdas)
- void f()
- {
- int i = 99;
- steal([&] { return &i; });
- }
+## F.def: Function definitions
- int main()
- {
- f();
- cout << *glob << '\n';
- }
-
-Here I managed to read the location abandoned by the call of `f`.
-The pointer stored in `glob` could be used much later and cause trouble in unpredictable ways.
+A function definition is a function declaration that also specifies the function's implementation, the function body.
-**Note**: The address of a local variable can be "returned"/leaked by a return statement,
-by a `T&` out-parameter, as a member of a returned object, as an element of a returned array, and more.
+### F.1: "Package" meaningful operations as carefully named functions
-**Note**: Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one;
-such examples are handled equivalently to leaks of pointers out of a function.
+##### Reason
-**See also**: Another way of getting dangling pointers is [pointer invalidation](#???).
-It can be detected/prevented with similar techniques.
+Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code.
+If something is a well-specified action, separate it out from its surrounding code and give it a name.
-**Enforcement**: Preventable through static analysis.
+##### Example, don't
+ void read_and_print(istream& is) // read and print an int
+ {
+ int x;
+ if (is >> x)
+ cout << "the int is " << x << '\n';
+ else
+ cerr << "no int on input\n";
+ }
-
-### F.44: Return a `T&` when "returning no object" isn't an option
+Almost everything is wrong with `read_and_print`.
+It reads, it writes (to a fixed `ostream`), it writes error messages (to a fixed `ostream`), it handles only `int`s.
+There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
+For a tiny example, this looks OK, but if the input operation, the output operation, and the error handling had been more complicated the tangled
+mess could become hard to understand.
-**Reason**: The language guarantees that a `T&` refers to an object, so that testing for `nullptr` isn't necessary.
+##### Note
-**See also**: The return of a reference must not imply transfer of ownership:
-[discussion of dangling pointer prevention](#???) and [discussion of ownership](#???).
+If you write a non-trivial lambda that potentially can be used in more than one place, give it a name by assigning it to a (usually non-local) variable.
-**Example**:
+##### Example
- ???
+ sort(a, b, [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); });
-**Enforcement**: ???
+Naming that lambda breaks up the expression into its logical parts and provides a strong hint to the meaning of the lambda.
+ auto lessT = [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); };
-
-### F.45: Don't return a `T&&`
+ sort(a, b, lessT);
-**Reason**: It's asking to return a reference to a destroyed temporary object. A `&&` is a magnet for temporary objects. This is fine when the reference to the temporary is being passed "downward" to a callee, because the temporary is guaranteed to outlive the function call. (See [F.24](#RF-pass-ref-ref) and [F.25](#Rf-pass-ref-move).) However, it's not fine when passing such a reference "upward" to a larger caller scope. See also [F54](#Rf-local-ref-ref).
+The shortest code is not always the best for performance or maintainability.
-For passthrough functions that pass in parameters (by ordinary reference or by perfect forwarding) and want to return values, use simple `auto` return type deduction (not `auto&&`).
+##### Exception
-**Example; bad**: If `F` returns by value, this function returns a reference to a temporary.
+Loop bodies, including lambdas used as loop bodies, rarely need to be named.
+However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
+The rule [Keep functions short and simple](#Rf-single) implies "Keep loop bodies short."
+Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be reusable.
- template
- auto&& wrapper(F f) {
- log_call(typeid(f)); // or whatever instrumentation
- return f();
- }
+##### Enforcement
-**Example; good**: Better:
-
- template
- auto wrapper(F f) {
- log_call(typeid(f)); // or whatever instrumentation
- return f();
- }
+* See [Keep functions short and simple](#Rf-single)
+* Flag identical and very similar lambdas used in different places.
-**Exception**: `std::move` and `std::forward` do return `&&`, but they are just casts -- used by convention only in expression contexts where a reference to a temporary object is passed along within the same expression before the temporary is destroyed. We don't know of any other good examples of returning `&&`.
+### F.2: A function should perform a single logical operation
-**Enforcement**: Flag any use of `&&` as a return type, except in `std::move` and `std::forward`.
+##### Reason
+A function that performs a single operation is simpler to understand, test, and reuse.
-
-### F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)
+##### Example
-**Reason**: Functions can't capture local variables or be declared at local scope; if you need those things, prefer a lambda where possible, and a handwritten function object where not. On the other hand, lambdas and function objects don't overload; if you need to overload, prefer a function (the workarounds to make lambdas overload are ornate). If either will work, prefer writing a function; use the simplest tool necessary.
+Consider:
-**Example**:
+ void read_and_print() // bad
+ {
+ int x;
+ cin >> x;
+ // check for errors
+ cout << x << "\n";
+ }
- // writing a function that should only take an int or a string -- overloading is natural
- void f(int);
- void f(const string&);
-
- // writing a function object that needs to capture local state and appear
- // at statement or expression scope -- a lambda is natural
- vector v = lots_of_work();
- for(int tasknum = 0; tasknum < max; ++tasknum) {
- pool.run([=, &v]{
- /*
- ...
- ... process 1/max-th of v, the tasknum-th chunk
- ...
- */
- });
- }
- pool.join();
+This is a monolith that is tied to a specific input and will never find another (different) use. Instead, break functions up into suitable logical parts and parameterize:
-**Exception**: Generic lambdas offer a concise way to write function templates and so can be useful even when a normal function template would do equally well with a little more syntax. This advantage will probably disappear in the future once all functions gain the ability to have Concept parameters.
+ int read(istream& is) // better
+ {
+ int x;
+ is >> x;
+ // check for errors
+ return x;
+ }
-**Enforcement**:
+ void print(ostream& os, int x)
+ {
+ os << x << "\n";
+ }
- * 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.
+These can now be combined where needed:
+ void read_and_print()
+ {
+ auto x = read(cin);
+ print(cout, x);
+ }
+If there was a need, we could further templatize `read()` and `print()` on the data type, the I/O mechanism, the response to errors, etc. Example:
-
-### F.51: Prefer overloading over default arguments for virtual functions
-??? possibly other situations?
+ auto read = [](auto& input, auto& value) // better
+ {
+ input >> value;
+ // check for errors
+ };
-**Reason**: Virtual function overrides do not inherit default arguments, leading to surprises.
+ void print(auto& output, const auto& value)
+ {
+ output << value << "\n";
+ }
-**Example; bad**:
+##### Enforcement
- class base {
- public:
- virtual int multiply(int value, int factor = 2) = 0;
- };
+* Consider functions with more than one "out" parameter suspicious. Use return values instead, including `tuple` for multiple return values.
+* Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
+* Consider functions with 7 or more parameters suspicious.
- class derived : public base {
- public:
- override int multiply(int value, int factor = 10);
- };
-
- derived d;
- base& b = d;
-
- b.multiply(10); // these two calls will call the same function but
- d.multiply(10); // with different arguments and so different results
+### F.3: Keep functions short and simple
-**Enforcement**: Flag all uses of default arguments in virtual functions.
+##### Reason
+Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes.
+Functions with complex control structures are more likely to be long and more likely to hide logical errors
-
-### F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms
+##### Example
-**Reason**: For efficiency and correctness, you nearly always want to capture by reference when using the lambda locally. This includes when writing or calling parallel algorithms that are local because they join before returning.
+Consider:
-**Example**: This is a simple three-stage parallel pipeline. Each `stage` object encapsulates a worker thread and a queue, has a `process` function to enqueue work, and in its destructor automatically blocks waiting for the queue to empty before ending the thread.
+ double simple_func(double val, int flag1, int flag2)
+ // simple_func: takes a value and calculates the expected ASIC output,
+ // given the two mode flags.
+ {
+ double intermediate;
+ if (flag1 > 0) {
+ intermediate = func1(val);
+ if (flag2 % 2)
+ intermediate = sqrt(intermediate);
+ }
+ else if (flag1 == -1) {
+ intermediate = func1(-val);
+ if (flag2 % 2)
+ intermediate = sqrt(-intermediate);
+ flag1 = -flag1;
+ }
+ if (abs(flag2) > 10) {
+ intermediate = func2(intermediate);
+ }
+ switch (flag2 / 10) {
+ case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
+ break;
+ case 2: return finalize(intermediate, 13.1);
+ default: break;
+ }
+ return finalize(intermediate, 0.);
+ }
- void send_packets( buffers& bufs ) {
- stage encryptor ([] (buffer& b){ encrypt(b); });
- stage compressor ([&](buffer& b){ compress(b); encryptor.process(b); });
- stage decorator ([&](buffer& b){ decorate(b); compressor.process(b); });
- for (auto& b : bufs) { decorator.process(b); }
- } // automatically blocks waiting for pipeline to finish
+This is too complex.
+How would you know if all possible alternatives have been correctly handled?
+Yes, it breaks other rules also.
-**Enforcement**: ???
+We can refactor:
+ double func1_muon(double val, int flag)
+ {
+ // ???
+ }
-
-### F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread
+ double func1_tau(double val, int flag1, int flag2)
+ {
+ // ???
+ }
-**Reason**: Pointers and references to locals shouldn't outlive their scope. Lambdas that capture by reference are just another place to store a reference to a local object, and shouldn't do so if they (or a copy) outlive the scope.
+ double simple_func(double val, int flag1, int flag2)
+ // simple_func: takes a value and calculates the expected ASIC output,
+ // given the two mode flags.
+ {
+ if (flag1 > 0)
+ return func1_muon(val, flag2);
+ if (flag1 == -1)
+ // handled by func1_tau: flag1 = -flag1;
+ return func1_tau(-val, flag1, flag2);
+ return 0.;
+ }
-**Example**:
+##### Note
- {
- // ...
-
- // a, b, c are local variables
- background_thread.queue_work([=]{ process(a,b,c); }); // want copies of a, b, and c
- }
+"It doesn't fit on a screen" is often a good practical definition of "far too large."
+One-to-five-line functions should be considered normal.
-**Enforcement**: ???
+##### Note
+Break large functions up into smaller cohesive and named functions.
+Small simple functions are easily inlined where the cost of a function call is significant.
+##### Enforcement
-
-# C: Classes and Class Hierarchies
+* Flag functions that do not "fit on a screen."
+ How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
+* Flag functions that are too complex. How complex is too complex?
+ You could use cyclomatic complexity. Try "more than 10 logical paths through." Count a simple switch as one path.
-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.
+### F.4: If a function might have to be evaluated at compile time, declare it `constexpr`
-Class rule summary:
+##### Reason
-* [C.1: Organize related data into structures (`struct`s or `class`es)](#Rc-org)
-* [C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently](#Rc-struct)
-* [C.3: Represent the distinction between an interface and an implementation using a class](#Rc-interface)
-* [C.4: Make a function a member only if it needs direct access to the representation of a class](#Rc-member)
-* [C.5: Place helper functions in the same namespace as the class they support](#Rc-member)
-* [C.6: Declare a member function that does not modify the state of its object `const`](#Rc-const)
+ `constexpr` is needed to tell the compiler to allow compile-time evaluation.
-Subsections:
+##### Example
-* [C.concrete: Concrete types](#SS-concrete)
-* [C.ctor: Constructors, assignments, and destructors](#SS-ctor)
-* [C.con: Containers and other resource handles](#SS-containers)
-* [C.lambdas: Function objects and lambdas](#SS-lambdas)
-* [C.hier: Class hierarchies (OOP)](SS-hier)
-* [C.over: Overloading and overloaded operators](#SS-overload)
-* [C.union: Unions](#SS-union)
+The (in)famous factorial:
+ constexpr int fac(int n)
+ {
+ constexpr int max_exp = 17; // constexpr enables max_exp to be used in Expects
+ Expects(0 <= n && n < max_exp); // prevent silliness and overflow
+ int x = 1;
+ for (int i = 2; i <= n; ++i) x *= i;
+ return x;
+ }
-
-### C.1: Organize related data into structures (`struct`s or `class`es)
+This is C++14.
+For C++11, use a recursive formulation of `fac()`.
-**Reason**: Ease of comprehension. If data is related (for fundamental reasons), that fact should be reflected in code.
+##### Note
-**Example**:
+`constexpr` does not guarantee compile-time evaluation;
+it just guarantees that the function can be evaluated at compile time for constant expression arguments if the programmer requires it or the compiler decides to do so to optimize.
- void draw(int x, int y, int x2, int y2); // BAD: unnecessary implicit relationships
- void draw(Point from, Point to) // better
+ constexpr int min(int x, int y) { return x < y ? x : y; }
-**Note**: A simple class without virtual functions implies no space or time overhead.
+ void test(int v)
+ {
+ int m1 = min(-1, 2); // probably compile-time evaluation
+ constexpr int m2 = min(-1, 2); // compile-time evaluation
+ int m3 = min(-1, v); // run-time evaluation
+ constexpr int m4 = min(-1, v); // error: cannot evaluate at compile time
+ }
-**Note**: From a language perspective `class` and `struct` differ only in the default visibility of their members.
+##### Note
-**Enforcement**: Probably impossible. Maybe a heuristic looking for date items used together is possible.
+Don't try to make all functions `constexpr`.
+Most computation is best done at run time.
+##### Note
-
-### C.2: Use `class` if the class has an invariant; use `struct` if the data members can vary independently
+Any API that might eventually depend on high-level run-time configuration or
+business logic should not be made `constexpr`. Such customization can not be
+evaluated by the compiler, and any `constexpr` functions that depended upon
+that API would have to be refactored or drop `constexpr`.
-**Reason**: Ease of comprehension. The use of `class` alerts the programmer to the need for an invariant
+##### Enforcement
-**Note**: An invariant is logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using `Expects`.
+Impossible and unnecessary.
+The compiler gives an error if a non-`constexpr` function is called where a constant is required.
-**Example**:
+### F.5: If a function is very small and time-critical, declare it `inline`
- struct Pair { // the members can vary independently
- string name;
- int volume;
- };
+##### Reason
-but
+Some optimizers are good at inlining without hints from the programmer, but don't rely on it.
+Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
+We are still waiting.
+Specifying inline (explicitly, or implicitly when writing member functions inside a class definition) encourages the compiler to do a better job.
- class Date {
- private:
- int y;
- Month m;
- char d; // day
- public:
- Date(int yy, Month mm, char dd); // validate that {yy,mm,dd} is a valid date and initialize
- // ...
- };
+##### Example
-**Enforcement**: Look for `struct`s with all data private and `class`es with public members.
+ inline string cat(const string& s, const string& s2) { return s + s2; }
+##### Exception
-
-### C.3: Represent the distinction between an interface and an implementation using a class
+Do not put an `inline` function in what is meant to be a stable interface unless you are certain that it will not change.
+An inline function is part of the ABI.
-**Reason**: an explicit distinction between interface and implementation improves readability and simplifies maintenance.
+##### Note
-**Example**:
+`constexpr` implies `inline`.
- class Date {
- // ... some representation ...
- public:
- Date();
- Date(int yy, Month mm, char dd); // validate that {yy,mm,dd} is a valid date and initialize
+##### Note
- int day() const;
- Month month() const;
- // ...
- };
+Member functions defined in-class are `inline` by default.
-For example, we can now change the representation of a `Date` without affecting its users (recompilation is likely, though).
+##### Exception
-**Note**: Using a class in this way to represent the distinction between interface and implementation is of course not the only way.
-For example, we can use a set of declarations of freestanding functions in a namespace,
-an abstract base class,
-or a template fuction with concepts to represent an interface.
-The most important issue is to explicitly distinguish between an interface and its implementation "details."
-Ideally, and typically, an interface is far more stable than its implementation(s).
+Function templates (including member functions of class templates `A::function()` and member function templates `A::function()`) are normally defined in headers and therefore inline.
-**Enforcement**: ???
-
+##### Note
-
-### C.4: Make a function a member only if it needs direct access to the representation of a class
+Consider making functions out of line if they are more than three statements and can be declared out of line (such as class member functions).
-**Reason**: Less coupling than with member functions, fewer functions that can cause trouble by modifying object state, reduces the number of functions that needs to be modified after a change in representation.
+### F.6: If your function must not throw, declare it `noexcept`
-**Example**:
+##### Reason
- class Date {
- // ... relatively small interface ...
- };
+If an exception is not supposed to be thrown, the program cannot be assumed to cope with the error and should be terminated as soon as possible. Declaring a function `noexcept` helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure.
- // helper functions:
- Date next_weekday(Date);
- bool operator==(Date, Date);
+##### Example
-The "helper functions" have no need for direct access to the representation of a `Date`.
+Put `noexcept` on every function written completely in C or in any other language without exceptions.
+The C++ Standard Library does that implicitly for all functions in the C Standard Library.
-**Note**: This rule becomes even better if C++17 gets "uniform function call." ???
+##### Note
-**Enforcement**: Look for member function that do not touch data members directly.
-The snag is that many member functions that do not need to touch data members directly do.
+`constexpr` functions can throw when evaluated at run time, so you might need conditional `noexcept` for some of those.
+##### Example
-
-### C.5: Place helper functions in the same namespace as the class they support
+You can use `noexcept` even on functions that can throw:
-**Reason**: A helper function is a function (usually supplied by the writer of a class) that does not need direct access to the representation of the class,
-yet is seen as part of the useful interface to the class.
-Placing them in the same namespace as the class makes their relationship to the class obvious and allows them to be found by argument dependent lookup.
+ vector collect(istream& is) noexcept
+ {
+ vector res;
+ for (string s; is >> s;)
+ res.push_back(s);
+ return res;
+ }
-**Example**:
-
- namespace Chrono { // here we keep time-related services
-
- class Time { /* ... */ };
- class Date { /* ... */ };
-
- // helper functions:
- bool operator==(Date,Date);
- Date next_weekday(Date);
- // ...
- }
-
-**Enforcement**:
+If `collect()` runs out of memory, the program crashes.
+Unless the program is crafted to survive memory exhaustion, that might be just the right thing to do;
+`terminate()` might generate suitable error log information (but after memory runs out it is hard to do anything clever).
-* Flag global functions taking argument types from a single namespace.
+##### Note
-
-
-### C.6: Declare a member function that does not modify the state of its object `const`
+You must be aware of the execution environment that your code is running when
+deciding whether to tag a function `noexcept`, especially because of the issue
+of throwing and allocation. Code that is intended to be perfectly general (like
+the standard library and other utility code of that sort) needs to support
+environments where a `bad_alloc` exception could be handled meaningfully.
+However, most programs and execution environments cannot meaningfully
+handle a failure to allocate, and aborting the program is the cleanest and
+simplest response to an allocation failure in those cases. If you know that
+your application code cannot respond to an allocation failure, it could be
+appropriate to add `noexcept` even on functions that allocate.
-**Reason**: More precise statement of design intent, better readability, more errors caught by the compiler, more optimization opportunities.
+Put another way: In most programs, most functions can throw (e.g., because they
+use `new`, call functions that do, or use library functions that reports failure
+by throwing), so don't just sprinkle `noexcept` all over the place without
+considering whether the possible exceptions can be handled.
-**Example**:
+`noexcept` is most useful (and most clearly correct) for frequently used,
+low-level functions.
- int Date::day() const { return d; }
+##### Note
-**Note**: [Do not cast away `const`](#Res-casts-const).
+Destructors, `swap` functions, move operations, and default constructors should never throw.
+See also [C.44](#Rc-default00).
-**Enforcement**: Flag non-`const` member functions that do not write to their objects
+##### Note
+Care must be taken on base virtual functions and functions part of a public interface because declaring a function `noexcept` is establishing a guarantee that all current and future implementations must abide by. For virtual function, all overriders must also be `noexcept` and removing `noexcept` from a function could break calling functions.
-
-## C.concrete: Concrete types
+##### Enforcement
-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.
-A value of regular type can be copied and the result of a copy is an independent object with the same value as the original.
-If a concrete type has both `=` and `==`, `a=b` should result in `a==b` being `true`.
-Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
-The C++ built-in types are regular, and so are standard-library classes, such as `string`, `vector`, and `map`.
-Concrete types are also often referred to as value types to distinguish them from types uses as part of a hierarchy.
+* (hard) Flag low-level functions that are not `noexcept`, yet cannot throw.
+* Flag throwing `swap`, `move`, destructors, and default constructors.
-Concrete type rule summary:
+### F.7: For general use, take `T*` or `T&` arguments rather than smart pointers
-* [C.10: Prefer a concrete type over more complicated classes](#Rc-concrete)
-* [C.11: Make a concrete types regular](#Rc-regular)
+##### Reason
+Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended.
+A function that does not manipulate lifetime should take raw pointers or references instead.
-
-### C.10 Prefer a concrete type over more complicated classes
+Passing by smart pointer restricts the use of a function to callers that use smart pointers.
+A function that needs a `widget` should be able to accept any `widget` object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
-**Reason**: A concrete type is fundamentally simpler than a hierarchy:
-easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.
-You need a reason (use cases) for using a hierarchy.
+Passing a shared smart pointer (e.g., `std::shared_ptr`) implies a run-time cost.
-**Example**
+##### Example
- class Point1 {
- int x, y;
- // ... operations ...
- // .. no virtual functions ...
- };
+ // accepts any int*
+ void f(int*);
- class Point2 {
- int x, y;
- // ... operations, some virtual ...
- virtual ~Point2();
- };
+ // can only accept ints for which you want to transfer ownership
+ void g(unique_ptr);
- void use()
- {
- Point1 p11 { 1,2}; // make an object on the stack
- Point1 p12 {p11}; // a copy
+ // can only accept ints for which you are willing to share ownership
+ void g(shared_ptr);
- auto p21 = make_unique(1,2); // make an object on the free store
- auto p22 = p21.clone(); // make a copy
+ // doesn't change ownership, but requires a particular ownership of the caller
+ void h(const unique_ptr&);
- // ...
- }
+ // accepts any int
+ void h(int&);
-If a class can be part of a hierarchy, we (in real code if not necessarily in small examples) must manipulate its objects through pointers or references.
-That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.
+##### Example, bad
-**Note**: Concrete types can be stack allocated and be members of other classes.
+ // callee
+ void f(shared_ptr& w)
+ {
+ // ...
+ use(*w); // only use of w -- the lifetime is not used at all
+ // ...
+ };
-**Note**: The use of indirection is fundamental for run-time polymorphic interfaces.
-The allocation/deallocation overhead is not (that's just the most common case).
-We can use a base class as the interface of a scoped object of a derived class.
-This is done where dynamic allocation is prohibited (e.g. hard real-time) and to provide a stable interface to some kinds of plug-ins.
+ // caller
+ shared_ptr my_widget = /* ... */;
+ f(my_widget);
-**Enforcement**: ???
+ widget stack_widget;
+ f(stack_widget); // error
+##### Example, good
-
-### C.11: Make a concrete types regular
+ // callee
+ void f(widget& w)
+ {
+ // ...
+ use(w);
+ // ...
+ };
-**Reason**: Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
+ // caller
+ shared_ptr my_widget = /* ... */;
+ f(*my_widget);
-**Example**:
+ widget stack_widget;
+ f(stack_widget); // ok -- now this works
- struct Bundle {
- string name;
- vector vr;
- };
+##### Note
- bool operator==(const Bundle& a, const Bundle& b) { return a.name==b.name && a.vr==b.vr; }
+We can catch many common cases of dangling pointers statically (see [lifetime safety profile](#SS-lifetime)). Function arguments naturally live for the lifetime of the function call, and so have fewer lifetime problems.
- Bundle b1 { "my bundle", {r1,r2,r3}};
- Bundle b2 = b1;
- if (!(b1==b2)) error("impossible!");
- b2.name = "the other bundle";
- if (b1==b2) error("No!");
+##### Enforcement
-In particular, if a concrete type has an assignment also give it an equals operator so that `a=b` implies `a==b`.
+* (Simple) Warn if a function takes a parameter of a smart pointer type (that overloads `operator->` or `operator*`) that is copyable but the function only calls any of: `operator*`, `operator->` or `get()`.
+ Suggest using a `T*` or `T&` instead.
+* Flag a parameter of a smart pointer type (a type that overloads `operator->` or `operator*`) that is copyable/movable but never copied/moved from in the function body, and that is never modified, and that is not passed along to another function that could do so. That means the ownership semantics are not used.
+ Suggest using a `T*` or `T&` instead.
-**Enforcement**: ???
+**See also**:
+* [Prefer `T*` over `T&` when "no argument" is a valid option](#Rf-ptr-ref)
+* [Smart pointer rule summary](#Rr-summary-smartptrs)
-
-## C.ctor: Constructors, assignments, and destructors
+### F.8: Prefer pure functions
-These functions control the lifecycle of objects: creation, copy, move, and destruction.
-Define constructors to guarantee and simplify initialization of classes.
+##### Reason
-These are *default operations*:
+Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
-* a default constructor: `X()`
-* a copy constructor: `X(const X&)`
-* a copy assignment: `operator=(const X&)`
-* a move constructor: `X(X&&)`
-* a a move assignment: `operator=(X&&)`
-* a destructor: `~X()`
+##### Example
-By default, the compiler defines each of these operations if it is used, but the default can be suppressed.
+ template
+ auto square(T t) { return t * t; }
-The default operations are a set of related operations that together implement the lifecycle semantics of an object.
-By default, C++ treats classes as value-like types, but not all types are value-like.
+##### Enforcement
-Set of default operations rules:
+Not possible.
-* [C.20: If you can avoid defining any default operations, do](#Rc-zero)
-* [C.21: If you define or `=delete` any default operation, define or `=delete` them all](#Rc-five)
-* [C.22: Make default operations consistent](#Rc-matched)
+### F.9: Unused parameters should be unnamed
-Destructor rules:
+##### Reason
-* [C.30: Define a destructor if a class needs an explicit action at object destruction](#Rc-dtor)
-* [C.31: All resources acquired by a class must be released by the class's destructor](#Rc-dtor-release)
-* [C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning](#Rc-dtor-ptr)
-* [C.33: If a class has an owning pointer member, define or `=delete` a destructor](#Rc-dtor-ptr)
-* [C.34: If a class has an owning reference member, define or `=delete` a destructor](#Rc-dtor-ref)
-* [C.35: A base class with a virtual function needs a virtual destructor](#Rc-dtor-virtual)
-* [C.36: A destructor may not fail](#Rc-dtor-fail)
-* [C.37: Make destructors `noexcept`](#Rc-dtor-noexcept)
+Readability.
+Suppression of unused parameter warnings.
-Constructor rules:
+##### Example
-* [C.40: Define a constructor if a class has an invariant](#Rc-ctor)
-* [C.41: A constructor should create a fully initialized object](#Rc-complete)
-* [C.42: If a constructor cannot construct a valid object, throw an exception](#Rc-throw)
-* [C.43: Give a class a default constructor](#Rc-default0)
-* [C.44: Prefer default constructors to be simple and non-throwing](#Rc-default00)
-* [C.45: Don't define a default constructor that only initializes data members; use member initializers instead](#Rc-default)
-* [C.46: By default, declare single-argument constructors `explicit`](#Rc-explicit)
-* [C.47: Define and initialize member variables in the order of member declaration](#Rc-order)
-* [C.48: Prefer in-class initializers to member initializers in constructors for constant initializers](#Rc-in-class-initializer)
-* [C.49: Prefer initialization to assignment in constructors](#Rc-initialize)
-* [C.50: Use a factory function if you need "virtual behavior" during initialization](#Rc-factory)
-* [C.51: Use delegating constructors to represent common actions for all constructors of a class](#Rc-delegating)
-* [C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization](#Rc-inheriting)
+ widget* find(const set& s, const widget& w, Hint); // once upon a time, a hint was used
-Copy and move rules:
+##### Note
-* [C.60: Make copy assignment non-`virtual`, take the parameter by `const&`, and return by non-`const&`](#Rc-copy-assignment)
-* [C.61: A copy operation should copy](#Rc-copy-semantic)
-* [C.62: Make copy assignment safe for self-assignment](#Rc-move-self)
-* [C.63: Make move assignment non-`virtual`, take the parameter by `&&`, and return by non-`const&`](#Rc-move-assignment)
-* [C.64: A move operation should move and leave its source in a valid state](#Rc-move-semantic)
-* [C.65: Make move assignment safe for self-assignment](#Rc-copy-self)
-* [C.66: Make move operations `noexcept`](#Rc-move-noexcept)
-* [C.67: A base class should suppress copying, and provide a virtual `clone` instead if "copying" is desired](#Rc-copy-virtual)
+Allowing parameters to be unnamed was introduced in the early 1980s to address this problem.
-Other default operations rules:
+If parameters are conditionally unused, declare them with the `[[maybe_unused]]` attribute.
+For example:
-* [C.80: Use `=default` if you have to be explicit about using the default semantics](#Rc-=default)
-* [C.81: Use `=delete` when you want to disable default behavior (without wanting an alternative)](#Rc-=delete)
-* [C.82: Don't call virtual functions in constructors and destructors](#Rc-ctor-virtual)
-* [C.83: For value-like types, consider providing a `noexcept` swap function](#Rc-swap)
-* [C.84: A `swap` may not fail](#Rc-swap-fail)
-* [C.85: Make `swap` `noexcept`](#Rc-swap-noexcept)
-* [C.86: Make `==` symmetric with respect of operand types and `noexcept`](#Rc-eq)
-* [C.87: Beware of `==` on base classes](#Rc-eq-base)
-* [C.88: Make `<` symmetric with respect of operand types and `noexcept`](#Rc-lt)
-* [C.89: Make a `hash` `noexcept`](#Rc-hash)
+ template
+ Value* find(const set& s, const Value& v, [[maybe_unused]] Hint h)
+ {
+ if constexpr (sizeof(Value) > CacheSize)
+ {
+ // a hint is used only if Value is of a certain size
+ }
+ }
+##### Enforcement
-
-## C.defop: Default Operations
+Flag named unused parameters.
-By default, the language supply the default operations with their default semantics.
-However, a programmer can disalble or replace these defaults.
+### F.10: If an operation can be reused, give it a name
+##### Reason
-
-### C.20: If you can avoid defining default operations, do
+Documentation, readability, opportunity for reuse.
-**Reason**: It's the simplest and gives the cleanest semantics.
+##### Example
-**Example**:
+ struct Rec {
+ string name;
+ string addr;
+ int id; // unique identifier
+ };
- struct Named_map {
- public:
- // ... no default operations declared ...
- private:
- string name;
- map rep;
- };
+ bool same(const Rec& a, const Rec& b)
+ {
+ return a.id == b.id;
+ }
- Named_map nm; // default construct
- Named_map nm2 {nm}; // copy construct
+ vector find_id(const string& name); // find all records for "name"
-Since `std::map` and `string` have all the special functions, not further work is needed.
+ auto x = find_if(vr.begin(), vr.end(),
+ [&](Rec& r) {
+ if (r.name.size() != n.size()) return false; // name to compare to is in n
+ for (int i = 0; i < r.name.size(); ++i)
+ if (tolower(r.name[i]) != tolower(n[i])) return false;
+ return true;
+ }
+ );
-**Note**: This is known as "the rule of zero".
+There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.
-**Enforcement**: (Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
- For example, a class with a (pointer,size) pair of member and a destructor that `delete`s the pointer could probably be converted to a `vector`.
+ bool compare_insensitive(const string& a, const string& b)
+ {
+ if (a.size() != b.size()) return false;
+ for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
+ return true;
+ }
+ auto x = find_if(vr.begin(), vr.end(),
+ [&](Rec& r) { return compare_insensitive(r.name, n); }
+ );
-
-### C.21: If you define or `=delete` any default operation, define or `=delete` them all
+Or maybe (if you prefer to avoid the implicit name binding to n):
-**Reason**: The semantics of the special functions are closely related, so it one needs to be non-default, the odds are that other need modification.
+ auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };
-**Example, bad**:
+ auto x = find_if(vr.begin(), vr.end(),
+ [](const Rec& r) { return cmp_to_n(r.name); }
+ );
- struct M2 { // bad: incomplete set of default operations
- public:
- // ...
- // ... no copy or move operations ...
- ~M2() { delete[] rep; }
- private:
- pair* rep; // zero-terminated set of pairs
- };
+##### Note
- void use()
- {
- M2 x;
- M2 y;
- // ...
- x = y; // the default assignment
- // ...
- }
+whether functions, lambdas, or operators.
-Given that "special attention" was needed for the destructor (here, to deallocate), the likelihood that copy and move assignment (both will implicitly destroy an object) are correct is low (here, we would get double deletion).
+##### Exception
-**Note**: This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor.
+* Lambdas logically used only locally, such as an argument to `for_each` and similar control flow algorithms.
+* Lambdas as [initializers](#???)
-**Note**: If you want a default implementation of a default operation (while defining another), write `=default` to show you're doing so intentionally for that function.
-If you don't want a default operation, suppress it with `=delete`.
+##### Enforcement
-**Note:** Compilers enforce much of this rule and ideally warn about any violation.
+* (hard) flag similar lambdas
+* ???
-**Note**: Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
+### F.11: Use an unnamed lambda if you need a simple function object in one place only
-**Enforcement**: (Simple) A class should have a declaration (even a `=delete` one) for either all or none of the special functions.
+##### Reason
+That makes the code concise and gives better locality than alternatives.
-
-### C.22: Make default operations consistent
+##### Example
-**Reason**: The default operations are conceptually a matched set. Their semantics is interrelated.
-Users will be surprised if copy/move construction and copy/move assignment do logically different things. Users will be surprised if constructors and destructors do not provide a consistent view of resource management. Users will be surprised if copy and move doesn't reflect the way constructors and destructors work.
+ auto earlyUsersEnd = std::remove_if(users.begin(), users.end(),
+ [](const User &a) { return a.id > 100; });
-**Example; bad**:
- class Silly { // BAD: Inconsistent copy operations
- class Impl {
- // ...
- };
- shared_ptr p;
- public:
- Silly(const Silly& a) : p{a.p} { *p = *a.p; } // deep copy
- Silly& operator=(const Silly& a) { p = a.p; } // shallow copy
- // ...
- };
+##### Exception
-These operations disagree about copy semantics. This will lead to confusion and bugs.
+Naming a lambda can be useful for clarity even if it is used only once.
-**Enforcement**:
+##### Enforcement
-* (Complex) A copy/move constructor and the corresponding copy/move assignment operator should write to the same member variables at the same level of dereference.
-* (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
-* (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
-* (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
+* Look for identical and near identical lambdas (to be replaced with named functions or named lambdas).
+## F.call: Parameter passing
+There are a variety of ways to pass parameters to a function and to return values.
-
-## C.dtor: Destructors
+### F.15: Prefer simple and conventional ways of passing information
-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).
+##### Reason
+Using "unusual and clever" techniques causes surprises, slows understanding by other programmers, and encourages bugs.
+If you really feel the need for an optimization beyond the common techniques, measure to ensure that it really is an improvement, and document/comment because the improvement might not be portable.
-
-### C.30: Define a destructor if a class needs an explicit action at object destruction
+The following tables summarize the advice in the following Guidelines, F.16-21.
-**Reason**: A destructor is implicitly invoked at the end of an objects lifetime.
-If the default destructor is sufficient, use it.
-Only if you need code that is not simply destructors of members executed, define a non-default destructor.
+Normal parameter passing:
-**Example**:
+
- template
- struct Final_action { // slightly simplified
- A act;
- Final_action(F a) :act{a} {}
- ~Final_action() { act(); }
- };
+Advanced parameter passing:
- template
- Final_action finally(A act) // deduce action type
- {
- return Final_action{a};
- }
+
- void test()
- {
- auto act = finally([]{ cout<<"Exit test\n"; }); // establish exit action
- // ...
- if (something) return; // act done here
- // ...
- } // act done here
+Use the advanced techniques only after demonstrating need, and document that need in a comment.
-The whole purpose of `Final_action` is to get a piece of code (usually a lambda) executed upon destruction.
+For passing sequences of characters see [String](#SS-string).
-**Note**: There are two general categories of classes that need a user-defined destructor:
+##### Exception
-* A class with a resource that is not already represented as a class with a destructor, e.g., a `vector` or a transaction class.
-* A class that exists primarily to execute an action upon destruction, such as a tracer or `Final_action`.
+To express shared ownership using `shared_ptr` types, rather than following guidelines F.16-21,
+follow [R.34](#Rr-sharedptrparam-owner), [R.35](#Rr-sharedptrparam), and [R.36](#Rr-sharedptrparam-const).
-**Example, bad**:
+### F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to `const`
- class Foo { // bad; use the default destructor
- public:
- // ...
- ~Foo() { s=""; i=0; vi.clear(); } // clean up
- private:
- string s;
- int i;
- vector vi;
- }
+##### Reason
-The default destructor does it better, more efficiently, and can't get it wrong.
+Both let the caller know that a function will not modify the argument, and both allow initialization by rvalues.
-**Note**: If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use `=default`.
+What is "cheap to copy" depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value.
+When copying is cheap, nothing beats the simplicity and safety of copying, and for small objects (up to two or three words) it is also faster than passing by reference because it does not require an extra indirection to access from the function.
-**Enforcement**: Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.
+##### Example
+ void f1(const string& s); // OK: pass by reference to const; always cheap
-
-### C.31: All resources acquired by a class must be released by the class's destructor
+ void f2(string s); // bad: potentially expensive
-**Reason**: Prevention of resource leaks, especially in error cases.
+ void f3(int x); // OK: Unbeatable
-**Note**: For resources represented as classes with a complete set of default operations, this happens automatically.
+ void f4(const int& x); // bad: overhead on access in f4()
-**Example**:
+For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:
- class X {
- ifstream f; // may own a file
- // ... no default operations defined or =deleted ...
- };
+* If the function is going to unconditionally move from the argument, take it by `&&`. See [F.18](#Rf-consume).
+* If the function is going to keep a locally modifiable copy of the argument only for its own local use, taking it by value is fine
+* If the function is going to keep a copy of the argument to pass to another destination (to another function, or store in a non-local location), in addition to passing by `const&` (for lvalues),
+ add an overload that passes the parameter by `&&` (for rvalues) and in the body `std::move`s it to its destination. Essentially this overloads a "will-move-from"; see [F.18](#Rf-consume).
+* In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See [F.19](#Rf-forward).
-`X`'s `ifstream` implicitly closes any file it may have open upon destruction of its `X`.
+##### Example
-**Example; bad**:
+ int multiply(int, int); // just input ints, pass by value
- class X2 { // bad
- FILE* f; // may own a file
- // ... no default operations defined or =deleted ...
- };
+ // suffix is input-only but not as cheap as an int, pass by const&
+ string& concatenate(string&, const string& suffix);
-`X2` may leak a file handle.
+ void sink(unique_ptr); // input only, and moves ownership of the widget
-**Note**: What about a sockets that won't close? A destructor, close, or cleanup operation [should never fail](#Rc-dtor-fail).
-If it does nevertheless, we have a problem that has no really good solution.
-For starters, the writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
-See [discussion](#Sd-never-fail).
-To make the problem worse, many "close/release" operations are not retryable.
-Many have tried to solve this problem, but no general solution is known.
-If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
+Avoid "esoteric techniques" such as passing arguments as `T&&` "for efficiency".
+Most rumors about performance advantages from passing by `&&` are false or brittle (but see [F.18](#Rf-consume) and [F.19](#Rf-forward)).
-**Note**: A class can hold pointers and references to objects that it does not own.
-Obviously, such objects should not be `delete`d by the class's destructor.
-For example:
+##### Notes
- Preprocessor pp { /* ... */ };
- Parser p { pp, /* ... */ };
- Type_checker tc { p, /* ... */ };
+A reference can be assumed to refer to a valid object (language rule).
+There is no (legitimate) "null reference."
+If you need the notion of an optional value, use a pointer, `std::optional`, or a special value used to denote "no value."
-Here `p` refers to `pp` but does not own it.
+##### Enforcement
-**Enforcement**:
+* (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than `2 * sizeof(void*)`.
+ Suggest using a reference to `const` instead.
+* (Simple) ((Foundation)) Warn when a parameter passed by reference to `const` has a size less or equal than `2 * sizeof(void*)`. Suggest passing by value instead.
+* (Simple) ((Foundation)) Warn when a parameter passed by reference to `const` is `move`d.
-* (Simple) If a class has pointer or reference member variables that are owners
-(e.g., deemed owners by using `GSL::owner`), then they should be referenced in its destructor.
-* (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership
-(e.g., look into the constructors).
+##### Exception
+To express shared ownership using `shared_ptr` types, follow [R.34](#Rr-sharedptrparam-owner) or [R.36](#Rr-sharedptrparam-const),
+depending on whether or not the function unconditionally takes a reference to the argument.
-
-### C.32: If a class has a raw pointer (`T*`) or reference (`T&`), consider whether it might be owning
+### F.17: For "in-out" parameters, pass by reference to non-`const`
-**Reason**: There is a lot of code that is non-specific about ownership.
+##### Reason
-**Example**:
+This makes it clear to callers that the object is assumed to be modified.
- ???
+##### Example
-**Note**: If the `T*` or `T&` is owning, mark it `owning`. If the `T*` is not owning, consider marking it `ptr`.
-This will aide documentation and analysis.
+ void update(Record& r); // assume that update writes to r
-**Enforcement**: Look at the initialization of raw member pointers and member references and see if an allocation is used.
+##### Note
+Some user-defined and standard library types, such as `span` or the iterators
+are [cheap to copy](#Rf-in) and may be passed by value, while doing so has
+mutable (in-out) reference semantics:
-
-### C.33: If a class has an owning pointer member, define a destructor
+ void increment_all(span a)
+ {
+ for (auto&& e : a)
+ ++e;
+ }
-**Reason**: An owned object must be `deleted` upon destruction of the object that owns it.
+##### Note
-**Example**: A pointer member may represent a resource.
-[A `T*` should not do so](#Rr-ptr), but in older code, that's common.
-Consider a `T*` a possible owner and therefore suspect.
+A `T&` argument can pass information into a function as well as out of it.
+Thus `T&` could be an in-out-parameter. That can in itself be a problem and a source of errors:
- template
- class Smart_ptr {
- T* p; // BAD: vague about ownership of *p
- // ...
- public:
- // ... no user-defined default operations ...
- };
+ void f(string& s)
+ {
+ s = "New York"; // non-obvious error
+ }
- void use(Smart_ptr p1)
- {
- auto p2 = p1; // error: p2.p leaked (if not nullptr and not owned by some other code)
- }
+ void g()
+ {
+ string buffer = ".................................";
+ f(buffer);
+ // ...
+ }
-Note that if you define a destructor, you must define or delete [all default operations](#Rc-five):
+Here, the writer of `g()` is supplying a buffer for `f()` to fill, but `f()` simply replaces it (at a somewhat higher cost than a simple copy of the characters).
+A bad logic error can happen if the writer of `g()` incorrectly assumes the size of the `buffer`.
- template
- class Smart_ptr2 {
- T* p; // BAD: vague about ownership of *p
- // ...
- public:
- // ... no user-defined copy operations ...
- ~Smart_ptr2() { delete p; } // p is an owner!
- };
+##### Enforcement
- void use(Smart_ptr p1)
- {
- auto p2 = p1; // error: double deletion
- }
+* (Moderate) ((Foundation)) Warn about functions regarding reference to non-`const` parameters that do *not* write to them.
+* (Simple) ((Foundation)) Warn when a non-`const` parameter being passed by reference is `move`d.
-The default copy operation will just copy the `p1.p` into `p2.p` leading to a double destruction of `p1.p`. Be explicit about ownership:
+### F.18: For "will-move-from" parameters, pass by `X&&` and `std::move` the parameter
- template
- class Smart_ptr3 {
- owner* p; // OK: explicit about ownership of *p
- // ...
- public:
- // ...
- // ... copy and move operations ...
- ~Smart_ptr3() { delete p; }
- };
+##### Reason
- void use(Smart_ptr3 p1)
- {
- auto p2 = p1; // error: double deletion
- }
+It's efficient and eliminates bugs at the call site: `X&&` binds to rvalues, which requires an explicit `std::move` at the call site if passing an lvalue.
+##### Example
- **Note**: Often the simplest way to get a destructor is to replace the pointer with a smart pointer (e.g., `std::unique_ptr`)
- and let the compiler arrange for proper destruction to be done implicitly.
-
-**Note**: Why not just require all owning pointers to be "smart pointers"?
- That would sometimes require non-trivial code changes and may affect ABIs.
+ void sink(vector&& v) // sink takes ownership of whatever the argument owned
+ {
+ // usually there might be const accesses of v here
+ store_somewhere(std::move(v));
+ // usually no more use of v here; it is moved-from
+ }
-**Enforcement**:
+Note that the `std::move(v)` makes it possible for `store_somewhere()` to leave `v` in a moved-from state.
+[That could be dangerous](#Rc-move-semantic).
-* A class with a pointer data member is suspect.
-* A class with an `owner` should define its default operations.
+##### Exception
-
-### C.34: If a class has an owning reference member, define a destructor
+Unique owner types that are move-only and cheap-to-move, such as `unique_ptr`, can also be passed by value which is simpler to write and achieves the same effect. Passing by value does generate one extra (cheap) move operation, but prefer simplicity and clarity first.
-**Reason**: A reference member may represent a resource.
-It should not do so, but in older code, that's common.
-See [pointer members and destructors](#Rc-dtor ptr).
-Also, copying may lead to slicing.
+For example:
-**Example, bad**:
+ template
+ void sink(std::unique_ptr p)
+ {
+ // use p ... possibly std::move(p) onward somewhere else
+ } // p gets destroyed
- class Handle { // Very suspect
- Shape& s; // use reference rather than pointer to prevent rebinding
- // BAD: vague about ownership of *p
- // ...
- public:
- Handle(Shape& ss) : s{ss} { /* ... */ }
- // ...
- };
+##### Exception
-The problem of whether `Handle` is responsible for the destruction of its `Shape` is the same as for the pointer case:
-If the `Handle` owns the object referred to by `s` it must have a destructor.
+If the "will-move-from" parameter is a `shared_ptr` follow [R.34](#Rr-sharedptrparam-owner) and pass the `shared_ptr` by value.
-**Example**:
+##### Enforcement
- class Handle { // OK
- owner s; // use reference rather than pointer to prevent rebinding
- // ...
- public:
- Handle(Shape& ss) : s{ss} { /* ... */ }
- ~Handle() { delete &s; }
- // ...
- };
+* Flag all `X&&` parameters (where `X` is not a template type parameter name) where the function body uses them without `std::move`.
+* Flag access to moved-from objects.
+* Don't conditionally move from objects
-Independently of whether `Handle` owns its `Shape`, we must consider the default copy operations suspect:
+### F.19: For "forward" parameters, pass by `TP&&` and only `std::forward` the parameter
- Handle x {*new Circle{p1,17}}; // the Handle had better own the Circle or we have a leak
- Handle y {*new Triangle{p1,p2,p3}};
- x = y; // the default assignment will try *x.s=*y.s
+##### Reason
-That `x=y` is highly suspect.
-Assigning a `Triangle` to a `Circle`?
-Unless `Shape` has its [copy assignment `=deleted`](#Rc-copy-virtual), only the `Shape` part of `Triangle` is copied into the `Circle`.
+If the object is to be passed onward to other code and not directly used by this function, we want to make this function agnostic to the argument `const`-ness and rvalue-ness.
+In that case, and only that case, make the parameter `TP&&` where `TP` is a template type parameter -- it both *ignores* and *preserves* `const`-ness and rvalue-ness. Therefore any code that uses a `TP&&` is implicitly declaring that it itself doesn't care about the variable's `const`-ness and rvalue-ness (because it is ignored), but that intends to pass the value onward to other code that does care about `const`-ness and rvalue-ness (because it is preserved). When used as a parameter `TP&&` is safe because any temporary objects passed from the caller will live for the duration of the function call. A parameter of type `TP&&` should essentially always be passed onward via `std::forward` in the body of the function.
-**Note**: Why not just require all owning references to be replaced by "smart pointers"?
- Changing from references to smart pointers implies code changes.
- We don't (yet) have smart references.
- Also, that may affect ABIs.
+##### Example
-**Enforcement**:
+Usually you forward the entire parameter (or parameter pack, using `...`) exactly once on every static control flow path:
-* A class with a reference data member is suspect.
-* A class with an `owner` reference should define its default operations.
+ template
+ inline decltype(auto) invoke(F&& f, Args&&... args)
+ {
+ return forward(f)(forward(args)...);
+ }
+##### Example
-
-### C.35: A base class with a virtual function needs a virtual destructor
+Sometimes you may forward a composite parameter piecewise, each subobject once on every static control flow path:
-**Reason**: To prevent undefined behavior.
-If an application attempts to delete a derived class object through a base class pointer, the result is undefined if the base class's destructor is non-virtual.
-In general, the writer of a base class does not know the appropriate action to be done upon destruction.
+ template
+ inline auto test(PairLike&& pairlike)
+ {
+ // ...
+ f1(some, args, and, forward(pairlike).first); // forward .first
+ f2(and, forward(pairlike).second, in, another, call); // forward .second
+ }
-**Example; bad**:
+##### Enforcement
- struct Base { // BAD: no virtual destructor
- virtual f();
- };
+* 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, or `std::forward`ing it more than once but qualified with a different data member exactly once on every static path.
- struct D : Base {
- string s {"a resource needing cleanup"};
- ~D() { /* ... do some cleanup ... */ }
- // ...
- };
+### F.20: For "out" output values, prefer return values to output parameters
- void use()
- {
- unique_ptr p = make_unique();
- // ...
- } // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
+##### Reason
-**Note**: A virtual function defines an interface to derived classes that can be used without looking at the derived classes.
-Someone using such an interface is likely to also destroy using that interface.
+A return value is self-documenting, whereas a `&` could be either in-out or out-only and is liable to be misused.
-**Note**: A destructor must be `public` or it will prevent stack allocation and normal heap allocation via smart pointer (or in legacy code explicit `delete`):
+This includes large objects like standard containers that use implicit move operations for performance and to avoid explicit memory management.
- class X {
- ~X(); // private destructor
- // ...
- };
+If you have multiple values to return, [use a tuple](#Rf-out-multi) or similar multi-member type.
- void use()
- {
- X a; // error: cannot destroy
- auto p = make_unique(); // error: cannot destroy
- }
+##### Example
-**Enforcement**: (Simple) A class with any virtual functions should have a virtual destructor.
+ // OK: return pointers to elements with the value x
+ vector find_all(const vector&, int x);
+ // Bad: place pointers to elements with value x in-out
+ void find_all(const vector&, vector& out, int x);
-
-### C.36: A destructor may not fail
+##### Note
-**Reason**: In general we do not know how to write error-free code if a destructor should fail.
-The standard library requires that all classes it deals with have destructors that do not exit by throwing.
+A `struct` of many (individually cheap-to-move) elements might be in aggregate expensive to move.
-**Example**:
+##### Exceptions
- class X {
- public:
- ~X() noexcept;
- // ...
- };
+* For non-concrete types, such as types in an inheritance hierarchy, return the object by `unique_ptr` or `shared_ptr`.
+* If a type is expensive to move (e.g., `array`), consider allocating it on the free store and return a handle (e.g., `unique_ptr`), or passing it in a reference to non-`const` target object to fill (to be used as an out-parameter).
+* To reuse an object that carries capacity (e.g., `std::string`, `std::vector`) across multiple calls to the function in an inner loop: [treat it as an in/out parameter and pass by reference](#Rf-out-multi).
- X::~X() noexcept
- {
- // ...
- if (cannot_release_a_resource) terminate();
- // ...
- }
+##### Example
-**Note**: Many have tried to devise a fool-proof scheme for dealing with failure in destructors.
-None have succeeded to come up with a general scheme.
-This can be be a real practical problem: For example, what about a sockets that won't close?
-The writer of a destructor does not know why the destructor is called and cannot "refuse to act" by throwing an exception.
-See discussion.
-To make the problem worse, many "close/release" operations are not retryable.
-If at all possible, consider failure to close/cleanup a fundamental design error and terminate.
+Assuming that `Matrix` has move operations (possibly by keeping its elements in a `std::vector`):
-**Note**: Declare a destructor `noexcept`. That will ensure that it either completes normally or terminate the program.
+ Matrix operator+(const Matrix& a, const Matrix& b)
+ {
+ Matrix res;
+ // ... fill res with the sum ...
+ return res;
+ }
-**Note**: If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow
-(maybe even by modifying some global state and hope something will notice and be able to take care of the problem).
-Be fully aware that this technique is special-purpose and error-prone.
-Consider the "my connection will not close" example.
-Probably there is a problem at the other end of the connection and only a piece of code responsible for both ends of the connection can properly handle the problem.
-The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.
+ Matrix x = m1 + m2; // move constructor
-**Note**: If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully
-(e.g., by using a different clean-up mechanism from the one that threw an exception).
+ y = m3 + m3; // move assignment
-**Enforcement**: (Simple) A destructor should be declared `noexcept`.
+##### Note
-
-### C.37: Make destructors `noexcept`
+The return value optimization doesn't handle the assignment case, but the move assignment does.
-**Reason**: [A destructor may not fail](#Rc-dtor fail). If a destructor tries to exit with an exception, it's a bad design error and the program had better terminate.
+##### Example
-**Enforcement**: (Simple) A destructor should be declared `noexcept`.
+ struct Package { // exceptional case: expensive-to-move object
+ char header[16];
+ char load[2024 - 16];
+ };
+ Package fill(); // Bad: large return value
+ void fill(Package&); // OK
+ int val(); // OK
+ void val(int&); // Bad: Is val reading its argument
-
-## C.ctor: Constructors
+##### Enforcement
-A constuctor defined how an object is initialized (constructed).
+* Flag reference to non-`const` parameters that are not read before being written to and are a type that could be cheaply returned; they should be "out" return values.
+### F.21: To return multiple "out" values, prefer returning a struct
-
-### C.40: Define a constructor if a class has an invariant
+##### Reason
-**Reason**: That's what constructors are for.
+A return value is self-documenting as an "output-only" value.
+Note that C++ does have multiple return values, by convention of using tuple-like types (`struct`, `array`, `tuple`, etc.),
+possibly with the extra convenience of structured bindings (C++17) at the call site.
+Prefer using a named `struct` if possible.
+Otherwise, a `tuple` is useful in variadic templates.
-**Example**:
+##### Example
- class Date { // a Date represents a valid date
- // in the January 1, 1900 to December 31, 2100 range
- Date(int dd, int mm, int yy)
- :d{dd}, m{mm}, y{yy}
- {
- if (!is_valid(d,m,y)) throw Bad_date{}; // enforce invariant
- }
- // ...
- private:
- int d,m,y;
- };
+ // BAD: output-only parameter documented in a comment
+ int f(const string& input, /*output only*/ string& output_data)
+ {
+ // ...
+ output_data = something();
+ return status;
+ }
-It is often a good idea to express the invariant as an `Ensure` on the constructor.
+ // GOOD: self-documenting
+ struct f_result { int status; string data; };
-**Note**: A constructor can be used for convenience even if a class does not have an invariant. For example:
+ f_result f(const string& input)
+ {
+ // ...
+ return {status, something()};
+ }
- struct Rec {
- string s;
- int i {0};
- Rec(const string& ss) : s{ss} {}
- Rec(int ii) :i{ii} {}
- };
+C++98's standard library used this style in places, by returning `pair` in some functions.
+For example, given a `set my_set`, consider:
- Rec r1 {7};
- Rec r2 {"Foo bar"};
+ // C++98
+ pair result = my_set.insert("Hello");
+ if (result.second)
+ do_something_with(result.first); // workaround
-**Note**: The C++11 initializer list rules eliminates the need for many constructors. For example:
+With C++17 we are able to use "structured bindings" to give each member a name:
- struct Rec2{
- string s;
- int i;
- Rec2(const string& ss, int ii = 0} :s{ss}, i{ii} {} // redundant
- };
+ if (auto [ iter, success ] = my_set.insert("Hello"); success)
+ do_something_with(iter);
- Rec r1 {"Foo",7};
- Rec r2 {"Bar"};
+A `struct` with meaningful names is more common in modern C++.
+See for example `ranges::min_max_result`, `from_chars_result`, and others.
-The `Rec2` constructor is redundant.
-Also, the default for `int` would be better done as a [member initializer](#Rc-in-class initializer).
+##### Exception
-**See also**: [construct valid object](#Rc-complete) and [constructor throws](#Rc-throw).
+Sometimes, we need to pass an object to a function to manipulate its state.
+In such cases, passing the object by reference [`T&`](#Rf-inout) is usually the right technique.
+Explicitly passing an in-out parameter back out again as a return value is often not necessary.
+For example:
-**Enforcement**:
+ istream& operator>>(istream& in, string& s); // much like std::operator>>()
-* Flag classes with user-define copy operations but no destructor (a user-defined copy is a good indicator that the class has an invariant)
+ for (string s; in >> s; ) {
+ // do something with line
+ }
+Here, both `s` and `in` are used as in-out parameters.
+We pass `in` by (non-`const`) reference to be able to manipulate its state.
+We pass `s` to avoid repeated allocations.
+By reusing `s` (passed by reference), we allocate new memory only when we need to expand `s`'s capacity.
+This technique is sometimes called the "caller-allocated out" pattern and is particularly useful for types,
+such as `string` and `vector`, that needs to do free store allocations.
-
-### C.41: A constructor should create a fully initialized object
+To compare, if we passed out all values as return values, we would write something like this:
-**Reason**: A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
+ struct get_string_result { istream& in; string s; };
-**Example; bad**:
+ get_string_result get_string(istream& in) // not recommended
+ {
+ string s;
+ in >> s;
+ return { in, move(s) };
+ }
- class X1 {
- FILE* f; // call init() before any other fuction
- // ...
- public:
- X1() {}
- void init(); // initialize f
- void read(); // read from f
- // ...
- };
+ for (auto [in, s] = get_string(cin); in; s = get_string(in).s) {
+ // do something with string
+ }
- void f()
- {
- X1 file;
- file.read(); // crash or bad read!
- // ...
- file.init(); // too late
- // ...
- }
+We consider that significantly less elegant with significantly less performance.
-Compilers do not read comments.
+For a truly strict reading of this rule (F.21), the exception isn't really an exception because it relies on in-out parameters,
+rather than the plain out parameters mentioned in the rule.
+However, we prefer to be explicit, rather than subtle.
-**Exception**: If a valid object cannot conveniently be constructed by a constructor [use a factory function](#C factory).
-
-**Note**: If a constructor acquires a resource (to create a valid object), that resource should be [released by the destructor](#Rc-release).
-The idiom of having constructors acquire resources and destructors release them is called [RAII](#Rr-raii) ("Resource Acquisitions Is Initialization").
-
-
-
-### C.42: If a constructor cannot construct a valid object, throw an exception
-
-**Reason**: Leaving behind an invalid object is asking for trouble.
-
-**Example**:
-
- class X2 {
- FILE* f; // call init() before any other fuction
- // ...
- public:
- X2(const string& name)
- :f{fopen(name.c_str(),"r"}
- {
- if (f==nullptr) throw runrime_error{"could not open" + name};
- // ...
- }
-
- void read(); // read from f
- // ...
- };
-
- void f()
- {
- X2 file {"Zeno"}; // throws if file isn't open
- file.read(); // fine
- // ...
- }
-
-**Example, bad**:
-
- class X3 { // bad: the constructor leaves a non-valid object behind
- FILE* f; // call init() before any other fuction
- bool valid;;
- // ...
- public:
- X3(const string& name)
- :f{fopen(name.c_str(),"r"}, valid{false}
- {
- if (f) valid=true;
- // ...
- }
-
- void is_valid()() { return valid; }
- void read(); // read from f
- // ...
- };
-
- void f()
- {
- X3 file {Heraclides"};
- file.read(); // crash or bad read!
- // ...
- if (is_valid()()) {
- file.read();
- // ...
- }
- else {
- // ... handle error ...
- }
- // ...
- }
-
-**Note**: For a variable definition (e.g., on the stack or as a member of another object) there is no explicit function call from which an error code could be returned. Leaving behind an invalid object an relying on users to consistently check an `is_valid()` function before use is tedious, error-prone, and inefficient.
-
-**Exception**: There are domains, such as some hard-real-time systems (think airplane controls) where (without additional tool support) exception handling is not sufficiently predictable from a timing perspective. There the `is_valed()` technique must be used. In such cases, check `is_valid()` consistently and immediately to simulate [RAII](#Rr-raii).
-
-**Alternative**: If you feel tempted to use some "post-constructor initialization" or "two-stage initialization" idiom, try not to do that. If you really have to, look at [factory functions](#Rc-factory).
-
-**Enforcement**:
-* (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.
+##### Note
+In most cases, it is useful to return a specific, user-defined type.
+For example:
-
-### C.43: Give a class a default constructor
+ struct Distance {
+ int value;
+ int unit = 1; // 1 means meters
+ };
-**Reason**: Many language and library facilities rely on default constructors,
-e.g. `T a[10]` and `std::vector v(10)` default initializes their elements.
+ Distance d1 = measure(obj1); // access d1.value and d1.unit
+ auto d2 = measure(obj2); // access d2.value and d2.unit
+ auto [value, unit] = measure(obj3); // access value and unit; somewhat redundant
+ // to people who know measure()
+ auto [x, y] = measure(obj4); // don't; it's likely to be confusing
-**Example**:
+The overly generic `pair` and `tuple` should be used only when the value returned represents independent entities rather than an abstraction.
- class Date {
- public:
- Date();
- // ...
- };
-
- vector vd1(1000); // default Date needed here
- vector vd2(1000,Date{Month::october,7,1885}); // alternative
+Another option is to use `optional` or `expected`, rather than `pair` or `tuple`.
+When used appropriately these types convey more information about what the members mean than `pair` or `pair` do.
-There is no "natural" default date (the big bang is too far back in time to be useful for most people), so this example is non-trivial.
-`{0,0,0}` is not a valid date in most calendar systems, so choosing that would be introducing something like floating-point's NaN.
-However, most realistic `Date` classes has a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.
-
-**Enforcement**:
-
-* Flag classes without a default constructor
-
-
-
-### C.44: Prefer default constructors to be simple and non-throwing
-
-**Reason**: Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
-
-**Example, problematic**:
-
- template
- class Vector0 { // elem points to space-elem element allocated using new
- public:
- Vector0() :Vector0{0} {}
- Vector0(int n) :elem{new T[n]}, space{elem+n}, last{elem} {}
- // ...
- private:
- own elem;
- T* space;
- T* last;
- };
-
-This is nice and general, but setting a `Vector0` to empty after an error involves an allocation, which may fail.
-Also, having a default `Vector` represented as `{new T[0],0,0}` seems wasteful.
-For example, `Vector0 v(100)` costs 100 allocations.
-
-**Example**:
-
- template
- class Vector1 { // elem is nullptr or elem points to space-elem element allocated using new
- public:
- Vector1() noexcept {} // sets the representation to {nullptr,nullptr,nullptr}; doesn't throw
- Vector1(int n) :elem{new T[n]}, space{elem+n}, last{elem} {}
- // ...
- private:
- own elem = nullptr;
- T* space = nullptr;
- T* last = nullptr;
- };
-
-Using `{nullptr,nullptr,nullptr}` makes `Vector1{}` cheap, but a special case and implies run-time checks.
-Setting a `Vector1` to empty after detecting an error is trivial.
+##### Note
-**Enforcement**:
+When the object to be returned is initialized from local variables that are expensive to copy,
+explicit `move` may be helpful to avoid copying:
-* Flag throwing default constructors
+ pair f(const string& input)
+ {
+ LargeObject large1 = g(input);
+ LargeObject large2 = h(input);
+ // ...
+ return { move(large1), move(large2) }; // no copies
+ }
+Alternatively,
-
-### C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
+ pair f(const string& input)
+ {
+ // ...
+ return { g(input), h(input) }; // no copies, no moves
+ }
-**Reason**: Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
+Note this is different from the `return move(...)` anti-pattern from [ES.56](#Res-move)
-**Example; bad**:
+##### Enforcement
- class X1 { // BAD: doesn't use member initializers
- string s;
- int i;
- public:
- X1() :s{"default"}, i{1} { }
- // ...
- };
+* Output parameters should be replaced by return values.
+ An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`.
+* `pair` or `tuple` return types should be replaced by `struct`, if possible.
+ In variadic templates, `tuple` is often unavoidable.
-**Example**:
+### F.60: Prefer `T*` over `T&` when "no argument" is a valid option
- class X2 {
- string s = "default";
- int i = 1;
- public:
- // use compiler-generated default constructor
- // ...
- };
+##### Reason
-
-**Enforcement**: (Simple) A default constructor should do more than just initialize member variables with constants.
+A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference".
+Sometimes having `nullptr` as an alternative to indicated "no object" is useful, but if it is not, a reference is notationally simpler and might yield better code.
+##### Example
-
-### C.46: By default, declare single-argument constructors explicit
+ string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
+ {
+ if (!p) return string{}; // p might be nullptr; remember to check
+ return string{p};
+ }
-**Reason**: To avoid unintended conversions.
+ void print(const vector& r)
+ {
+ // r refers to a vector; no check needed
+ }
-**Example; bad**:
+##### Note
- class String {
- // ...
- public:
- String(int); // BAD
- // ...
- };
+It is possible, but not valid C++ to construct a reference that is essentially a `nullptr` (e.g., `T* p = nullptr; T& r = *p;`).
+That error is very uncommon.
- String s = 10; // surprise: string of size 10
+##### Note
+If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null` provides the same guarantee as `T&`.
-**Exception**: If you really want an implicit conversion from the constructor argument type to the class type, don't use `explicit`:
+##### Enforcement
- class Complex {
- // ...
- public:
- Complex(double d); // OK: we want a conversion from d to {d,0}
- // ...
- };
+* Flag ???
- Complex z = 10.7; // unsurprising conversion
+### F.22: Use `T*` or `owner` to designate a single object
-**See also**: [Discussion of implicit conversions](#Ro-conversion).
+##### Reason
-**Enforcement**: (Simple) Single-argument constructors should be declared `explicit`. Good single argument non-`explicit` constructors are rare in most code based. Warn for all that are not on a "positive list".
+Readability: it makes the meaning of a plain pointer clear.
+Enables significant tool support.
+##### Note
-
-### C.47: Define and initialize member variables in the order of member declaration
+In traditional C and C++ code, plain `T*` is used for many weakly-related purposes, such as:
-**Reason**: To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
+* Identify a (single) object (not to be deleted by this function)
+* Point to an object allocated on the free store (and delete it later)
+* Hold the `nullptr`
+* Identify a C-style string (zero-terminated array of characters)
+* Identify an array with a length specified separately
+* Identify a location in an array
-**Example; bad**:
+This makes it hard to understand what the code does and is supposed to do.
+It complicates checking and tool support.
- class Foo {
- int m1;
- int m2;
- public:
- Foo(int x) :m2{x}, m1{++x} { } // BAD: misleading initializer order
- // ...
- };
+##### Example
- Foo x(1); // surprise: x.m1==x.m2==2
+ void use(int* p, int n, char* s, int* q)
+ {
+ p[n - 1] = 666; // Bad: we don't know if p points to n elements;
+ // assume it does not or use span
+ cout << s; // Bad: we don't know if that s points to a zero-terminated array of char;
+ // assume it does not or use zstring
+ delete q; // Bad: we don't know if *q is allocated on the free store;
+ // assume it does not or use owner
+ }
-**Enforcement**: (Simple) A member initializer list should mention the members in the same order they are declared.
+better
-**See also**: [Discussion](#Sd order)
+ void use2(span p, zstring s, owner q)
+ {
+ p[p.size() - 1] = 666; // OK, a range error can be caught
+ cout << s; // OK
+ delete q; // OK
+ }
+##### Note
-
-### C.48: Prefer in-class initializers to member initializers in constructors for constant initializers
+`owner` represents ownership, `zstring` represents a C-style string.
-**Reason**: Makes it explicit that the same value is expected to be used in all constructors. Avoids repetition. Avoids maintenance problems. It leads to the shortest and most efficient code.
+**Also**: Assume that a `T*` obtained from a smart pointer to `T` (e.g., `unique_ptr`) points to a single element.
-**Example; bad**:
+**See also**: [Support library](#gsl-guidelines-support-library)
- class X { // BAD
- int i;
- string s;
- int j;
- public:
- X() :i{666}, s{"qqq"} { } // j is uninitialized
- X(int ii) :i{ii} {} // s is "" and j is uninitialized
- // ...
- };
+**See also**: [Do not pass an array as a single pointer](#Ri-array)
-How would a maintainer know whether `j` was deliberately uninitialized (probably a poor idea anyway) and whether it was intentional to give `s` the default value `""` in one case and `qqq` in another (almost certainly a bug)? The problem with `j` (forgetting to initialize a member) often happens when a new member is added to an existing class.
+##### Enforcement
-**Example**:
+* (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.
- class X2 {
- int i {666};
- string s {"qqq"};
- int j {0};
- public:
- X2() = default; // all members are initialized to their defaults
- X2(int ii) :i{ii} {} // s and j initialized to their defaults
- // ...
- };
+### F.23: Use a `not_null` to indicate that "null" is not a valid value
-**Alternative**: We can get part of the benefits from default arguments to constructors, and that is not uncommon in older code. However, that is less explicit, causes more arguments to be passed, and is repetitive when there is more than one constructor:
+##### Reason
- class X3 { // BAD: inexplicit, argument passing overhead
- int i;
- string s;
- int j;
- public:
- X3(int ii = 666, const string& ss = "qqq", int jj = 0)
- :i{ii}, s{ss}, j{jj} { } // all members are initialized to their defaults
- // ...
- };
+Clarity. A function with a `not_null` parameter makes it clear that the caller of the function is responsible for any `nullptr` checks that might be necessary.
+Similarly, a function with a return value of `not_null` makes it clear that the caller of the function does not need to check for `nullptr`.
-**Enforcement**:
-* (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
-* (Simple) Default arguments to constructors suggest an in-class initalizer may be more appropriate.
+##### Example
+`not_null` makes it obvious to a reader (human or machine) that a test for `nullptr` is not necessary before dereference.
+Additionally, when debugging, `owner` and `not_null` can be instrumented to check for correctness.
-
-### C.49: Prefer initialization to assignment in constructors
+Consider:
-**Reason**: An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
+ int length(Record* p);
-**Example; good**:
+When I call `length(p)` should I check if `p` is `nullptr` first? Should the implementation of `length()` check if `p` is `nullptr`?
- class A { // Good
- string s1;
- public:
- A() : s1{"Hello, "} { } // GOOD: directly construct
- // ...
- };
+ // it is the caller's job to make sure p != nullptr
+ int length(not_null p);
-**Example; bad**:
+ // the implementor of length() must assume that p == nullptr is possible
+ int length(Record* p);
- class B { // BAD
- string s1;
- public:
- B() { s1 = "Hello, "; } // BAD: default constructor followed by assignment
- // ...
- };
+##### Note
- class C { // UGLY, aka very bad
- int* p;
- public:
- C() { cout << *p; p = new int{10}; } // accidental use before initialized
- // ...
- };
+A `not_null` is assumed not to be the `nullptr`; a `T*` might be the `nullptr`; both can be represented in memory as a `T*` (so no run-time overhead is implied).
+##### Note
+`not_null` is not just for built-in pointers. It works for `unique_ptr`, `shared_ptr`, and other pointer-like types.
-
-### C.50: Use a factory function if you need "virtual behavior" during initialization
+##### Enforcement
-**Reason**: If the state of a base class object must depend on the state of a derived part of the object,
- we need to use a virtual function (or equivalent) while minimizing the window of opportunity to misuse an imperfectly constructed object.
+* (Simple) Warn if a raw pointer is dereferenced without being tested against `nullptr` (or equivalent) within a function, suggest it is declared `not_null` instead.
+* (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against `nullptr` (or equivalent) within the function and sometimes is not.
+* (Simple) Warn if a `not_null` pointer is tested against `nullptr` within a function.
-**Example; bad**:
+### F.24: Use a `span` or a `span_p` to designate a half-open sequence
- class B {
- public:
- B()
- {
- // ...
- f(); // BAD: virtual call in constructor
- //...
- }
+##### Reason
- virtual void f() = 0;
+Informal/non-explicit ranges are a source of errors.
- // ...
- };
+##### Example
-**Example*:
+ X* find(span r, const X& v); // find v in r
- class B {
- private:
- B() { /* ... */ } // create an imperfectly initialized object
+ vector vec;
+ // ...
+ auto p = find({vec.begin(), vec.end()}, X{}); // find X{} in vec
- virtual void PostInitialize() // to be called right after construction
- {
- // ...
- f(); // GOOD: virtual dispatch is safe
- // ...
- }
+##### Note
- public:
- virtual void f() = 0;
+Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure.
+In particular, given a pair of arguments `(p, n)` designating an array `[p:p+n)`,
+it is in general impossible to know if there really are `n` elements to access following `*p`.
+`span` and `span_p` are simple helper classes designating a `[p:q)` range and a range starting with `p` and ending with the first element for which a predicate is true, respectively.
- template
- static shared_ptr Create() // interface for creating objects
- {
- auto p = make_shared();
- p->PostInitialize();
- return p;
- }
- };
+##### Example
- class D : public B { /* "¦ */ }; // some derived class
+A `span` represents a range of elements, but how do we manipulate elements of that range?
- shared_ptr p = D::Create(); // creating a D object
+ void f(span