Permalink
Find file
655bbca Jan 2, 2017
19225 lines (12931 sloc) 672 KB

C++ Core Guidelines

December 12, 2016

Editors:

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.7. 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. 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. We plan to modify and extend this document as our understanding improves and the language and the set of available libraries improve. When commenting, please note the introduction that outlines our aims and general approach. The list of contributors is here.

Problems:

  • The sets of rules have not been thoroughly 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

You can read an explanation of the scope and structure of this Guide or just jump straight in:

Supporting sections:

or look at a specific language feature

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

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). 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. 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.

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 emphasizes safety (of various forms) and simplicity. They may very well be too strict. We expect to have to introduce more exceptions to better accommodate real-world needs. We also need more rules.

You will find some of the rules contrary to your expectations or even contrary to your experience. If we haven't suggested you change your coding style in any way, we have failed! Please try to verify or disprove rules! In particular, we'd really like to have some of our rules backed up with measurements or better examples.

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.

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.

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

This is a set of core guidelines for modern C++, C++14, 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:

In.target: Target readership

All C++ programmers. This includes programmers who might consider C.

In.aims: Aims

The purpose of this document is to help developers to adopt modern C++ (C++11, C++14, and soon C++17) and to achieve a more uniform style across code bases.

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!

Take the time to understand the implications of a guideline rule on your program.

These guidelines are designed according to the "subset of superset" principle (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) 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.

Many of the rules are prescriptive. 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 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. 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 your level of programming to glorified assembly code.

The rules are designed to allow gradual adoption.

Some rules aim to increase various forms of safety while others aim to reduce the likelihood of accidents, many do both. 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

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 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. You can browse through them using the links. However, their main intended use is to be targets for tools. That is, a tool looks for violations and the tool returns links to violated rules. The rules then provide reasons, examples of potential consequences of the violation, and suggested remedies.

These guidelines are not intended to be a substitute for a tutorial treatment of C++. 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 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.

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.

The rules are not intended to force you to write in an impoverished subset of C++. They are emphatically not meant to define a, say, Java-like subset of C++. They are not meant to define a single "one true C++" language. We value expressiveness and uncompromised performance.

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 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

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.

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 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 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 fat". 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):

  • 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:

[[suppress(tag)]]

where "tag" is the anchor name of the item where the Enforcement rule appears (e.g., for C.134 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, or bounds.2).

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 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.
  • Reasons (rationales) -- because programmers find it hard to follow rules they don't understand
  • Examples -- because rules are hard to understand in the abstract; can be positive or negative
  • Alternatives -- for "don't do this" rules
  • Exceptions -- 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 alsos -- references to related rules and/or further discussion (in this document or elsewhere)
  • Notes (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. Also, we assume that the rules will be refined over time to make them more precise and checkable.

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 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, enter an Issue explaining your concerns and possibly a corresponding PR.

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.

In.sec: Major sections

Supporting sections:

These sections are not orthogonal.

Each section (e.g., "P" for "Philosophy") and each subsection (e.g., "C.hier" for "Class Hierarchies (OOP)") have an abbreviation for ease of searching and reference. The main section abbreviations are also used in rule numbers (e.g., "C.11" for "Make concrete types regular").

P: Philosophy

The rules in this section are very general.

Philosophy rules summary:

Philosophical rules are generally not mechanically checkable. However, individual rules reflecting these philosophical themes are. Without a philosophical basis the more concrete/specific/checkable rules lack rationale.

P.1: Express ideas directly in code

Reason

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.

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 f(vector<string>& v)
{
    string val;
    cin >> val;
    // ...
    int index = -1;                    // bad
    for (int i = 0; i < v.size(); ++i)
        if (v[i] == val) {
            index = i;
            break;
        }
    // ...
}

That loop is a restricted form of std::find. A much clearer expression of intent would be:

void f(vector<string>& 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 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 guideline support library, and use it appropriately.

Example
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

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.

  • use const consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)
  • flag uses of casts (casts neuter the type system)
  • detect code that mimics the standard library (hard)

P.2: Write in ISO Standard C++

Reason

This is a set of guidelines for writing ISO Standard C++.

Note

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.

Extensions often do not have rigorously defined semantics. Even extensions that are common and implemented by multiple compilers may 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.

Note

Using valid ISO C++ does not guarantee portability (let alone correctness). Avoid dependence on undefined behavior (e.g., undefined order of evaluation) and be aware of constructs with implementation defined meaning (e.g., sizeof(int)).

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 an extension of these Coding Guidelines customized to the specific environment.

Enforcement

Use an up-to-date C++ compiler (currently C++11 or C++14) with a set of options that do not accept extensions.

P.3: Express intent

Reason

Unless the intent of some code is stated (e.g., in names or comments), it is impossible to tell whether the code does what it is supposed to do.

Example
int 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 may or may not be intended. The reader cannot know from just this section of code.

Better:

for (const auto& x : v) { /* do something with x */ }

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 */ }

Sometimes better still, use a named algorithm:

for_each(v, [](int x) { /* do something with x */ });
for_each(par, v, [](int x) { /* do something with 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

Note

Alternative formulation: Say what should be done, rather than just how it should be done.

Note

Some language constructs express intent better than others.

Example

If two ints are meant to be the coordinates of a 2D point, say so:

draw_line(int, int, int, int);  // obscure
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(span<T>) interfaces
  • loop variables in too large a scope
  • naked new and delete
  • 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

Reason

Ideally, a program would be completely statically (compile-time) type safe. Unfortunately, that is not possible. Problem areas:

  • unions
  • casts
  • array decay
  • range errors
  • narrowing conversions
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. Always suggest an alternative. For example:

  • 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

Reason

Code clarity and performance. You don't need to write error handlers for errors caught at compile time.

Example
// 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"

This example is easily simplified

// Int is an alias used for integers
static_assert(sizeof(Int) >= 4);    // do: compile-time check
Example
void read(int* p, int n);   // read max n integers into *p

int a[100];
read(a, 1000);    // bad

better

void read(span<int> r); // read into the range of integers r

int a[100];
read(a);        // better: let the compiler figure out the number of elements

Alternative formulation: Don't postpone to run time what can be done well at compile time.

Enforcement
  • Look for pointer arguments.
  • Look for run-time checks for range violations.

P.6: What cannot be checked at compile time should be checkable at run time

Reason

Leaving hard-to-detect errors in a program is asking for crashes and bad results.

Note

Ideally we catch all errors (that are not errors in the programmer's logic) at either compile-time or run-time. It is impossible to catch all errors at compile time and often not affordable to catch all remaining errors at run time. However, we should endeavor to write programs that in principle can be checked, given sufficient resources (analysis programs, run-time checks, machine resources, time).

Example, bad
// separately compiled, possibly dynamically loaded
extern void f(int* p);

void g(int n)
{
    // bad: the number of elements is not passed to f()
    f(new int[n]);
}

Here, a crucial bit of information (the number of elements) has been so thoroughly "obscured" that static analysis is probably rendered infeasible and dynamic checking can be very difficult when f() is part of an ABI so that we cannot "instrument" that pointer. We could embed helpful information into the free store, but that requires global changes to a system and maybe to the compiler. What we have here is a design that makes error detection very hard.

Example, bad

We can of course pass the number of elements along with the pointer:

// separately compiled, possibly dynamically loaded
extern void f2(int* p, int n);

void g2(int n)
{
    f2(new int[n], m);  // bad: a wrong number of elements can be passed to f()
}

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.

Also, it is implicit that f2() is supposed to delete its argument (or did the caller make a second mistake?).

Example, bad

The standard library resource management pointers fail to pass the size when they point to an object:

// separately compiled, possibly dynamically loaded
// NB: this assumes the calling code is ABI-compatible, using a
// compatible C++ compiler and the same stdlib implementation
extern void f3(unique_ptr<int[]>, int n);

void g3(int n)
{
    f3(make_unique<int[]>(n), m);    // bad: pass ownership and size separately
}
Example

We need to pass the pointer and the number of elements as an integral object:

extern void f4(vector<int>&);   // separately compiled, possibly dynamically loaded
extern void f4(span<int>);      // 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<int> v(n);
    f4(v);                     // pass a reference, retain ownership
    f4(span<int>{v});          // pass a view, retain ownership
}

This design carries the number of elements along as an integral part of an object, so that errors are unlikely and dynamic (run-time) checking is always feasible, if not always affordable.

Example

How do we transfer both ownership and all information needed for validating use?

vector<int> f5(int n)    // OK: move
{
    vector<int> v(n);
    // ... initialize v ...
    return v;
}

unique_ptr<int[]> f6(int n)    // bad: loses n
{
    auto p = make_unique<int[]>(n);
    // ... initialize *p ...
    return p;
}

owner<int*> f7(int n)    // bad: loses n and we might forget to delete
{
    owner<int*> 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)-style interfaces (this will flag a lot of examples that can't be fixed for compatibility reasons)
  • ???

P.7: Catch run-time errors early

Reason

Avoid "mysterious" crashes. Avoid errors leading to (possibly unrecognized) wrong results.

Example
void increment1(int* p, int n)    // bad: error prone
{
    for (int i = 0; i < n; ++i) ++p[i];
}

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
    // ...
}

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. 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:

void increment2(span<int> 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):

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

void 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 a 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. 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)).

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?
    }

    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 of the possibility for measurement errors.

???

Enforcement
  • 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
  • ???

P.8: Don't leak any resources

Reason

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.

Example, bad
void f(char* name)
{
    FILE* input = fopen(name, "r");
    // ...
    if (something) return;   // bad: if something == true, a file handle is leaked
    // ...
    fclose(input);
}

Prefer RAII:

void f(char* name)
{
    ifstream input {name};
    // ...
    if (something) return;   // OK: no leak
    // ...
}

See also: The resource management section

Note

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

Enforcing the lifetime profile eliminates leaks. When combined with resource safety provided by RAII, it eliminates the need for "garbage collection" (by generating no garbage). Combine this with enforcement of the type and bounds profiles and you get complete type- and resource-safety, guaranteed by tools.

Enforcement
  • Look at pointers: Classify them into non-owners (the default) and owners. Where feasible, replace owners with standard-library resource handles (as in the example above). Alternatively, mark an owner as such using owner from the 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. "Another benefit of striving for efficiency is that the process forces you to understand the problem in more depth." - Alex Stepanov

Example, bad
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];
    if (buf == nullptr) 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 (int i = 0; i < x.s.size(); ++i) x.s[i] = buf[i];  // copy buf into x.s
    delete buf;
    return x;
}

void driver()
{
    X x = waste("Typical argument");
    // ...
}

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.

Example, bad
void lower(zstring s)
{
    for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}

Yes, this is an example from production code. We leave it to the reader to figure out what's wasted.

Note

An individual example of waste is rarely significant, and where it is significant, it is typically easily eliminated by an expert. However, waste spread liberally across a code base can easily be significant and experts are not always as available as we would like. The aim of this rule (and the more specific rules that 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.

Enforcement

Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.

P.10: Prefer immutable data to mutable data

Reason

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.

See Con: Constants and Immutability

P.11: Encapsulate messy constructs, rather than spreading through the code

Reason

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.

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;
    // ...
}

This is low-level, verbose, and error-prone. For example, we "forgot" to test for memory exhaustion. Instead, we could use vector:

vector<int> v;
v.reserve(100);
// ...
for (int x; cin >> x; ) {
    // ... check that x is valid ...
    v.push_back(x);
}
Note

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 that underlies these guidelines.

Enforcement
  • Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.

I: Interfaces

An interface is a contract between two parts of a program. Precisely stating what is expected of a supplier of a service and a user of that service is essential. Having good (easy-to-understand, encouraging efficient use, not error-prone, supporting testing, etc.) interfaces is probably the most important single aspect of code organization.

Interface rule summary:

See also

I.1: Make interfaces explicit

Reason

Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.

Example, bad

Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:

int rnd(double d)
{
    return (rnd_up) ? ceil(d) : d;    // don't: "invisible" dependency
}

It will not be obvious to a caller that the meaning of two calls of rnd(7.2) might give different results.

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 otherwise fixed semantics.

Example, bad

Reporting through non-local variables (e.g., errno) is easily ignored. For example:

// don't: no test of printf's return value
fprintf(connection, "logging: %d %d %d\n", x, y, s);

What if the connection goes down so that no logging output is produced? See I.??.

Alternative: Throw an exception. An exception cannot be ignored.

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.

Alternative formulation: An interface should be a function or a set of functions. Functions can be template functions and sets of functions can be classes or class templates.

Enforcement
  • (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.
  • (Simple) A function should not write to variables declared at namespace scope.

I.2 Avoid global variables

Reason

Non-const global variables hide dependencies and make the dependencies subject to unpredictable changes.

Example
struct Data {
    // ... lots of stuff ...
} data;            // non-const data

void compute()     // don't
{
    // ... use data ...
}

void output()     // don't
{
    // ... use data ...
}

Who else might modify data?

Note

Global constants are useful.

Note

The rule against global variables applies to namespace scope variables as well.

Alternative: If you use global (more generally namespace scope) data to avoid copying, consider passing the data as an object by reference to const. Another solution is to define the data as the state of some object and the operations as member functions.

Warning: Beware of data races: If one thread can access nonlocal data (or data passed by reference) while another thread executes the callee, we can have a data race. Every pointer or reference to mutable data is a potential data race.

Note

You cannot have a race condition on immutable data.

References: See the rules for calling functions.

Enforcement

(Simple) Report all non-const variables declared at namespace scope.

I.3: Avoid singletons

Reason

Singletons are basically complicated global objects in disguise.

Example
class Singleton {
    // ... lots of stuff to ensure that only one Singleton object is created,
    // that it is initialized properly, etc.
};

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.

Exception

You can use the simplest "singleton" (so simple that it is often not considered a singleton) to get initialization on first use, if any:

X& myX()
{
    static X my_x {3};
    return my_x;
}

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).

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:

X& myX()
{
    static auto p = new X {3};
    return *p;  // potential leak
}

Now someone has to delete that object in some suitably thread-safe way. That's error-prone, so we don't use that technique unless

  • myX is in multithreaded 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.

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.

  • 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

Reason

Types are the simplest and best documentation, have well-defined meaning, and are guaranteed to be checked at compile time. Also, precisely typed code is often optimized better.

Example, don't

Consider:

void pass(void* data);    // void* is suspicious

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*, especially in interfaces. Consider using a variant or a pointer to base instead.

Alternative: Often, a template parameter can eliminate the void* turning it into a T* or T&. For generic code these Ts can be general or concept constrained template parameters.

Example, bad

Consider:

void draw_rect(int, int, int, int);   // great opportunities for mistakes

draw_rect(p.x, p.y, 10, 20);          // what does 10, 20 mean?

An int can carry arbitrary forms of information, so we must guess about the meaning of the four ints. 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:

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

Obviously, we cannot catch all errors through the static type system (e.g., the fact that a first argument is supposed to be a top-left point is left to convention (naming and comments)).

Example, bad

In the following example, it is not clear from the interface what time_to_blink means: Seconds? Milliseconds?

void blink_led(int time_to_blink) // bad -- the unit is ambiguous
{
    // ...
    // do something with time_to_blink
    // ...
}

void use()
{
    blink_led(2);
}
Example, good

std::chrono::duration types (C++11) helps making the unit of time duration explicit.

void blink_led(milliseconds time_to_blink) // good -- the unit is explicit
{
    // ...
    // do something with time_to_blink
    // ...
}

void use()
{
    blink_led(1500ms);
}

The function can also be written in such a way that it will accept any time duration unit.

template<class rep, class period>
void blink_led(duration<rep, period> time_to_blink) // good -- accepts any unit
{
    // assuming that millisecond is the smallest relevant unit
    auto milliseconds_to_blink = duration_cast<milliseconds>(time_to_blink);
    // ...
    // do something with milliseconds_to_blink
    // ...
}

void use()
{
    blink_led(2s);
    blink_led(1500ms);
}
Enforcement
  • (Simple) Report the use of void* as a parameter or return type.
  • (Hard to do well) Look for member functions with many built-in type arguments.

I.5: State preconditions (if any)

Reason

Arguments have meaning that may constrain their proper use in the callee.

Example

Consider:

double sqrt(double x);

Here x must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:

double sqrt(double x); // x must be nonnegative

Some preconditions can be expressed as assertions. For example:

double sqrt(double x) { Expects(x >= 0); /* ... */ }

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.

Note

Prefer a formal specification of requirements, such as Expects(p != nullptr);. If that is infeasible, use English text in comments, such as // the sequence [p:q) is ordered using <.

Note

Most member functions have as a precondition that some class invariant holds. That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class. We don't need to mention it for each member function.

Enforcement

(Not enforceable)

See also: The rules for passing pointers. ???

I.6: Prefer Expects() for expressing preconditions

Reason

To make it clear that the condition is a precondition and to enable tool use.

Example
int area(int height, int width)
{
    Expects(height > 0 && width > 0);            // good
    if (height <= 0 || width <= 0) my_error();   // obscure
    // ...
}
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

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) we will adopt the standard version of preconditions, postconditions, and assertions.

Note

Expects() can also be used to check a condition in the middle of an algorithm.

Enforcement

(Not enforceable) Finding the variety of ways preconditions can be asserted is not feasible. Warning about those that can be easily identified (assert()) has questionable value in the absence of a language facility.

I.7: State postconditions

Reason

To detect misunderstandings about the result and possibly catch erroneous implementations.

Example, bad

Consider:

int area(int height, int width) { return height * width; }  // bad

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:

int area(int height, int width)
{
    auto res = height * width;
    Ensures(res > 0);
    return res;
}
Example, bad

Consider a famous security bug:

void f()    // problematic
{
    char buffer[MAX];
    // ...
    memset(buffer, 0, MAX);
}

There was no postcondition stating that the buffer should be cleared and the optimizer eliminated the apparently redundant memset() call:

void f()    // better
{
    char buffer[MAX];
    // ...
    memset(buffer, 0, MAX);
    Ensures(buffer[0] == 0);
}
Note

Postconditions are often informally stated in a comment that states the purpose of a function; Ensures() can be used to make this more systematic, visible, and checkable.

Note

Postconditions are especially important when they relate to something that is not directly reflected in a returned result, such as a state of a data structure used.

Example

Consider a function that manipulates a Record, using a mutex to avoid race conditions:

mutex m;

void manipulate(Record& r)    // don't
{
    m.lock();
    // ... no m.unlock() ...
}

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 manipulate(Record& r)    // postcondition: m is unlocked upon exit
{
    m.lock();
    // ... no m.unlock() ...
}

The bug is now obvious (but only to a human reading comments).

Better still, use RAII to ensure that the postcondition ("the lock must be released") is enforced in code:

void manipulate(Record& r)    // best
{
    lock_guard<mutex> _ {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.

Enforcement

(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

Reason

To make it clear that the condition is a postcondition and to enable tool use.

Example
void f()
{
    char buffer[MAX];
    // ...
    memset(buffer, 0, MAX);
    Ensures(buffer[0] == 0);
}
Note

Postconditions can be stated in many ways, including comments, if-statements, and assert(). This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.

Alternative: Postconditions of the form "this resource must be released" are best expressed by RAII.

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) we will adopt the standard version of preconditions, postconditions, and assertions.

Enforcement

(Not enforceable) Finding the variety of ways postconditions can be asserted is not feasible. Warning about those that can be easily identified (assert()) has questionable value in the absence of a language facility.

I.9: If an interface is a template, document its parameters using concepts

Reason

Make the interface precisely specified and compile-time checkable in the (not so distant) future.

Example

Use the ISO Concepts TS style of requirements specification. For example:

template<typename Iter, typename Val>
// requires InputIterator<Iter> && EqualityComparable<ValueType<Iter>>, Val>
Iter find(Iter first, Iter last, Val v)
{
    // ...
}
Note

Soon (maybe in 2017), most compilers will be able to check requires clauses once the // is removed. For now, the concept TS is supported only in GCC 6.1.

See also: Generic programming and concepts.

Enforcement

(Not yet enforceable) A language facility is under specification. When the language facility is available, warn if any non-variadic template parameter is not constrained by a concept (in its declaration or mentioned in a requires clause).

I.10: Use exceptions to signal a failure to perform a required task

Reason

It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state. This is a major source of errors.

Example
int printf(const char* ...);    // bad: return negative number if output fails

template <class F, class ...Args>
// good: throw system_error if unable to start the new thread
explicit thread(F&& f, Args&&... args);
Note

What is an error?

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 always has to check. However, if failing to make a connection is considered an error, then a failure should throw an exception.

Exception

Many traditional interface functions (e.g., UNIX signal handlers) use error codes (e.g., errno) to report what are really status codes, rather than errors. You don't have a good alternative to using such, so calling these does not violate the rule.

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:

int val;
int error_code;
tie(val, error_code) = do_something();
if (error_code == 0) {
    // ... handle the error or exit ...
}
// ... use val ...

This style unfortunately leads to uninitialized variables. A facility structured bindings to deal with that will become available in C++17.

[val, error_code] = do_something();
if (error_code == 0) {
    // ... handle the error or exit ...
}
// ... use val ...
Note

We don't consider "performance" a valid reason not to use exceptions.

  • Often, explicit error checking and handling consume as much time and space as exception handling.
  • Often, cleaner code yields better performance with exceptions (simplifying the tracing of paths through the program and their optimization).
  • A good rule for performance critical code is to move checking outside the critical part of the code (checking).
  • In the longer term, more regular code gets better optimized.
  • Always carefully measure before making performance claims.

See also: I.5 and I.7 for reporting precondition and postcondition violations.

Enforcement
  • (Not enforceable) This is a philosophical guideline that is infeasible to check directly.
  • Look for errno.

I.11: Never transfer ownership by a raw pointer (T*)

Reason

If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.

Example

Consider:

X* compute(args)    // don't
{
    X* res = new X{};
    // ...
    return res;
}

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):

vector<double> compute(args)  // good
{
    vector<double> res(10000);
    // ...
    return res;
}

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.

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 guideline support library:

owner<X*> compute(args)    // It is now clear that ownership is transferred
{
    owner<X*> res = new X{};
    // ...
    return res;
}

This tells analysis tools that res is an owner. That is, its value must be deleted or transferred to another owner, as is done here by the return.

owner is used similarly in the implementation of resource handles.

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."

See also: Argument passing and value return.

Enforcement
  • (Simple) Warn on delete of a raw pointer that is not an owner.
  • (Simple) Warn on failure to either reset or explicitly delete an owner pointer on every code path.
  • (Simple) Warn if the return value of new or a function call with return value of pointer type is assigned to a raw pointer.

I.12: Declare a pointer that must not be null as not_null

Reason

To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for nullptr.

Example
int length(const char* p);            // it is not clear whether length(nullptr) is valid

length(nullptr);                      // OK?

int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr

int length(const char* p);            // we must assume that p can be nullptr

By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.

Note

not_null is defined in the guideline support library.

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 czstring in preference to const char*.

// 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<zstring> p);

Note: length() is, of course, std::strlen() in disguise.

Enforcement
  • (Simple) ((Foundation)) If a function checks a pointer parameter against nullptr before access, on all control-flow paths, then warn it should be declared not_null.
  • (Complex) If a function with pointer return value ensures it is not nullptr on all return paths, then warn the return type should be declared not_null.

I.13: Do not pass an array as a single pointer

Reason

(pointer, size)-style interfaces are error-prone. Also, a plain pointer (to array) must rely on some convention to allow the callee to determine the size.

Example

Consider:

void copy_n(const T* p, T* q, int n); // copy from [p:p+n) to [q:q+n)

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.

Alternative

Consider using explicit spans:

void copy(span<const T> r, span<T> r2); // copy r to r2
Example, bad

Consider:

void draw(Shape* p, int n);  // poor interface; poor code
Circle arr[10];
// ...
draw(arr, 10);

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.

Alternative: Use a support class that ensures that the number of elements is correct and prevents dangerous implicit conversions. For example:

void draw2(span<Circle>);
Circle arr[10];
// ...
draw2(span<Circle>(arr));  // deduce the number of elements
draw2(arr);    // deduce the element type and array size

void draw3(span<Shape>);
draw3(arr);    // error: cannot convert Circle[10] to span<Shape>

This draw2() passes the same amount of information to draw(), but makes the fact that it is supposed to be a range of Circles explicit. See ???.

Exception

Use zstring and czstring to represent a C-style, zero-terminated strings. But when doing so, use string_span from the GSL to prevent range errors.

Enforcement
  • (Simple) ((Bounds)) Warn for any expression that would rely on implicit conversion of an array type to a pointer type. Allow exception for zstring/czstring pointer types.
  • (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. Allow exception for zstring/czstring pointer types.

I.22: Avoid complex initialization of global objects

Reason

Complex initialization can lead to undefined order of execution.

Example
// file1.c

extern const X x;

const Y y = f(x);   // read x; write y

// file2.c

extern const Y y;

const X x = g(y);   // read y; write x

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 particular example shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global variables.

Note

Order of initialization problems become particularly difficult to handle in concurrent code. It is usually best to avoid global (namespace scope) objects altogether.

Enforcement
  • 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

Reason

Having many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.

Example

The standard-library merge() is at the limit of what we can comfortably handle

template<class InputIterator1, class InputIterator2, class OutputIterator, class Compare>
OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
                     InputIterator2 first2, InputIterator2 last2,
                     OutputIterator result, Compare comp);

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 <:

template<class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
                     InputIterator2 first2, InputIterator2 last2,
                     OutputIterator result);

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:

template<class InputRange1, class InputRange2, class OutputIterator>
OutputIterator merge(InputRange1 r1, InputRange2 r2, OutputIterator result);

Grouping arguments into "bundles" is a general technique to reduce the number of arguments and to increase the opportunities for checking.

Alternatively, we could use concepts (as defined by the ISO TS) to define the notion of three types that must be usable for merging:

Mergeable{In1 In2, Out}
OutputIterator merge(In1 r1, In2 r2, Out result);
Note

How many arguments are too many? Four arguments is a lot. There are functions that are best expressed with four individual arguments, but not many.

Alternative: Group arguments into meaningful objects and pass the objects (by value or by reference).

Alternative: Use default arguments or overloads to allow the most common forms of calls to be done with fewer arguments.

Enforcement
  • 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.

I.24: Avoid adjacent unrelated parameters of the same type

Reason

Adjacent arguments of the same type are easily swapped by mistake.

Example, bad

Consider:

void copy_n(T* p, T* q, int n);  // copy from [p:p+n) to [q:q+n)

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:

void copy_n(const T* p, T* q, int n);  // copy from [p:p+n) to [q:q+n)
Exception

If the order of the parameters is not important, there is no problem:

int max(int a, int b);
Alternative

Don't pass arrays as pointers, pass an object representing a range (e.g., a span):

void copy_n(span<const T> p, span<T> q);  // copy from p to q
Alternative

Define a struct as the parameter type and name the fields for those parameters accordingly:

struct SystemParams {
    string config_file;
    string output_path;
    seconds timeout;
};
void initialize(SystemParams p);

This has a tendency to make invocations of this clear to future readers, as the parameters are often filled in by name at the call site.

Enforcement

(Simple) Warn if two consecutive parameters share the same type.

I.25: Prefer abstract classes as interfaces to class hierarchies

Reason

Abstract classes are more likely to be stable than base classes with state.

Example, bad

You just knew that Shape would turn up somewhere :-)

class Shape {  // bad: interface class loaded with data
public:
    Point center() const { return c; }
    virtual void draw() const;
    virtual void rotate(int);
    // ...
private:
    Point c;
    vector<Point> outline;
    Color col;
};

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 Shapes are best represented without an outline defined as a sequence of Points. Abstract classes were invented to discourage users from writing such classes:

class Shape {    // better: Shape is a pure interface
public:
    virtual Point center() const = 0;   // pure virtual function
    virtual void draw() const = 0;
    virtual void rotate(int) = 0;
    // ...
    // ... no data members ...
};
Enforcement

(Simple) Warn if a pointer to a class C is assigned to a pointer to a base of C and the base class contains data members.

I.26: If you want a cross-compiler ABI, use a C-style subset

Reason

Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.

Exception

You can carefully craft an interface using a few carefully selected higher-level C++ types. See ???.

Exception

Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.

Note

If you use a single compiler, you can use full C++ in interfaces. That may require recompilation after an upgrade to a new compiler version.

Enforcement

(Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.

F: Functions

A function specifies an action or a computation that takes the system from one consistent state to the next. It is the fundamental building block of programs.

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.

Function rule summary:

Function definition rules:

Parameter passing expression rules:

Parameter passing semantic rules:

Value return semantic rules:

Other function rules:

Functions have strong similarities to lambdas and function objects so see also Section ???.

F.def: Function definitions

A function definition is a function declaration that also specifies the function's implementation, the function body.

F.1: "Package" meaningful operations as carefully named functions

Reason

Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code. If something is a well-specified action, separate it out from its surrounding code and give it a name.

Example, don't
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 writes error messages (to a fixed ostream), it handles only ints. 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.

Note

If you write a non-trivial lambda that potentially can be used in more than one place, give it a name by assigning it to a (usually non-local) variable.

Example
sort(a, b, [](T x, T y) { return x.rank() < y.rank() && x.value() < y.value(); });

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(); };

sort(a, b, lessT);
find_if(a, b, lessT);

The shortest code is not always the best for performance or maintainability.

Exception

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 implies "Keep loop bodies short." Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be re-usable.

Enforcement

F.2: A function should perform a single logical operation

Reason

A function that performs a single operation is simpler to understand, test, and reuse.

Example

Consider:

void read_and_print()    // bad
{
    int x;
    cin >> x;
    // check for errors
    cout << x << "\n";
}

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:

int read(istream& is)    // better
{
    int x;
    is >> x;
    // check for errors
    return x;
}

void print(ostream& os, int x)
{
    os << x << "\n";
}

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:

auto read = [](auto& input, auto& value)    // better
{
    input >> value;
    // check for errors
};

auto print(auto& output, const auto& value)
{
    output << value << "\n";
}
Enforcement
  • Consider functions with more than one "out" parameter suspicious. Use return values instead, including tuple for multiple return values.
  • Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
  • Consider functions with 7 or more parameters suspicious.

F.3: Keep functions short and simple

Reason

Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes. Functions with complex control structures are more likely to be long and more likely to hide logical errors

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: break;
    }
    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 breaks other rules also.

We can refactor:

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)
        // handled by func1_tau: flag1 = -flag1;
        return func1_tau(-val, flag1, flag2);
    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

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
  • 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 path through." Count a simple switch as one path.

F.4: If a function may have to be evaluated at compile time, declare it constexpr

Reason

constexpr is needed to tell the compiler to allow compile-time evaluation.

Example

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;
}

This is C++14. For C++11, use a recursive formulation of fac().

Note

constexpr does not guarantee compile-time evaluation; it just guarantees that the function can be evaluated at compile time for constant expression arguments if the programmer requires it or the compiler decides to do so to optimize.

constexpr int min(int x, int y) { return x < y ? x : y; }

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

constexpr functions are pure: they can have no side effects.

int dcount = 0;
constexpr int double(int v)
{
    ++dcount;   // error: attempted side effect from constexpr function
    return v + v;
}

This is usually a very good thing.

When given a non-constant argument, a constexpr function can throw. If you consider exiting by throwing a side-effect, a constexpr function isn't completely pure; if not, this is not an issue. ??? A question for the committee: can a constructor for an exception thrown by a constexpr function modify state? "No" would be a nice answer that matches most practice.

Note

Don't try to make all functions constexpr. Most computation is best done at run time.

Note

Any API that may eventually depend on high-level runtime configuration or business logic should not be made constexpr. Such customization can not be evaluated by the compiler, and any constexpr functions that depend upon that API will have to be refactored or drop constexpr.

Enforcement

Impossible and unnecessary. The compiler gives an error if a non-constexpr function is called where a constant is required.

F.5: If a function is very small and time-critical, declare it inline

Reason

Some optimizers are good at inlining without hints from the programmer, but don't rely on it. Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans. We are still waiting. Specifying inline encourages the compiler to do a better job.

Example
inline string cat(const string& s, const string& s2) { return s + s2; }
Exception

Do not put an inline function in what is meant to be a stable interface unless you are really sure that it will not change. An inline function is part of the ABI.

Note

constexpr implies inline.

Note

Member functions defined in-class are inline by default.

Exception

Template functions (incl. template member functions) must be in headers and therefore inline.

Enforcement

Flag inline functions that are more than three statements and could have been declared out of line (such as class member functions).

F.6: If your function may not throw, declare it noexcept

Reason

If an exception is not supposed to be thrown, the program cannot be assumed to cope with the error and should be terminated as soon as possible. Declaring a function noexcept helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure.

Example

Put noexcept on every function written completely in C or in any other language without exceptions. The C++ standard library does that implicitly for all functions in the C standard library.

Note

constexpr functions cannot throw, so you don't need to use noexcept for those.

Example

You can use noexcept even on functions that can throw:

vector<string> collect(istream& is) noexcept
{
    vector<string> res;
    for (string s; is >> s;)
        res.push_back(s);
    return res;
}

If collect() runs out of memory, the program crashes. Unless the program is crafted to survive memory exhaustion, that may be just the right thing to do; terminate() may generate suitable error log information (but after memory runs out it is hard to do anything clever).

Note

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 may be handled meaningfully. However, the majority of 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 may be appropriate to add noexcept even on functions that allocate.

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.

noexcept is most useful (and most clearly correct) for frequently used, low-level functions.

Note

Destructors, swap functions, move operations, and default constructors should never throw.

Enforcement
  • Flag functions that are not noexcept, yet cannot throw.
  • Flag throwing swap, move, destructors, and default constructors.

F.7: For general use, take T* or T& arguments rather than smart pointers

Reason

Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended (see R.30). Passing by smart pointer restricts the use of a function to callers that use smart pointers. Passing a shared smart pointer (e.g., std::shared_ptr) implies a run-time cost.

Example
// accepts any int*
void f(int*);

// can only accept ints for which you want to transfer ownership
void g(unique_ptr<int>);

// can only accept ints for which you are willing to share ownership
void g(shared_ptr<int>);

// doesn't change ownership, but requires a particular ownership of the caller
void h(const unique_ptr<int>&);

// accepts any int
void h(int&);
Example, bad
// callee
void f(shared_ptr<widget>& w)
{
    // ...
    use(*w); // only use of w -- the lifetime is not used at all
    // ...
};

See further in R.30.

Note

We can catch dangling pointers statically, so we don't need to rely on resource management to avoid violations from dangling pointers.

See also: when to prefer T* and when to prefer T&.

See also: Discussion of smart pointer use.

Enforcement

Flag a parameter of a smart pointer type (a type that overloads operator-> or operator*) for which the ownership semantics are not used; that is

  • copyable but never copied/moved from or movable but never moved
  • and that is never modified or passed along to another function that could do so.

F.8: Prefer pure functions

Reason

Pure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.

Example
template<class T>
auto square(T t) { return t * t; }
Note

constexpr functions are pure.

When given a non-constant argument, a constexpr function can throw. If you consider exiting by throwing a side-effect, a constexpr function isn't completely pure; if not, this is not an issue. ??? A question for the committee: can a constructor for an exception thrown by a constexpr function modify state? "No" would be a nice answer that matches most practice.

Enforcement

Not possible.

F.call: Parameter passing

There are a variety of ways to pass parameters to a function and to return values.

F.15: Prefer simple and conventional ways of passing information

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.

The following tables summarize the advice in the following Guidelines, F.16-21.

Normal parameter passing:

Normal parameter passing table

Advanced parameter passing:

Advanced parameter passing table

Use the advanced techniques only after demonstrating need, and document that need in a comment.

F.16: For "in" parameters, pass cheaply-copied types by value and others by reference to const

Reason

Both let the caller know that a function will not modify the 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. 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.

Example
void f1(const string& s);  // OK: pass by reference to const; always cheap

void f2(string s);         // bad: potentially expensive

void f3(int x);            // OK: Unbeatable

void f4(const int& x);     // bad: overhead on access in f4()

For advanced uses (only), where you really need to optimize for rvalues passed to "input-only" parameters:

  • If the function is going to unconditionally move from the argument, take it by &&. See F.18.
  • If the function is going to keep a copy of the argument, in addition to passing by const& (for lvalues), add an overload that passes the parameter by && (for rvalues) and in the body std::moves it to its destination. Essentially this overloads a "consume"; see F.18.
  • In special cases, such as multiple "input + copy" parameters, consider using perfect forwarding. See F.19.
Example
int multiply(int, int); // just input ints, pass by value

// suffix is input-only but not as cheap as an int, pass by const&
string& concatenate(string&, const string& suffix);

void sink(unique_ptr<widget>);  // input only, and consumes the widget

Avoid "esoteric techniques" such as:

  • Passing arguments as T&& "for efficiency". Most rumors about performance advantages from passing by && are false or brittle (but see F.25.)
  • Returning const T& from assignments and similar operations (see F.47.)
Example

Assuming that Matrix has move operations (possibly by keeping its elements in a std::vector):

Matrix operator+(const Matrix& a, const Matrix& b)
{
    Matrix res;
    // ... fill res with the sum ...
    return res;
}

Matrix x = m1 + m2;  // move constructor

y = m3 + m3;         // move assignment
Notes

The return value optimization doesn't handle the assignment case, but the move assignment does.

A reference may be assumed to refer to a valid object (language rule). There is no (legitimate) "null reference." If you need the notion of an optional value, use a pointer, std::optional, or a special value used to denote "no value."

Enforcement
  • (Simple) ((Foundation)) Warn when a parameter being passed by value has a size greater than 4 * sizeof(int). Suggest using a reference to const instead.
  • (Simple) ((Foundation)) Warn when a const parameter being passed by reference has a size less than 3 * sizeof(int). Suggest passing by value instead.
  • (Simple) ((Foundation)) Warn when a const parameter being passed by reference is moved.

F.17: For "in-out" parameters, pass by reference to non-const

Reason

This makes it clear to callers that the object is assumed to be modified.

Example
void update(Record& r);  // assume that update writes to r
Note

A T& argument can pass information into a function as well as well as out of it. Thus T& could be an in-out-parameter. That can in itself be a problem and a source of errors:

void f(string& s)
{
    s = "New York";  // non-obvious error
}

void 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.

Enforcement
  • (Moderate) ((Foundation)) Warn about functions with reference to non-const parameters that do not write to them.
  • (Simple) ((Foundation)) Warn when a non-const parameter being passed by reference is moved.

F.18: For "consume" parameters, pass by X&& and std::move the parameter

Reason

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
void sink(vector<int>&& 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
}

Note that the std::move(v) makes it possible for store_somewhere() to leave v in a moved-from state. That could be dangerous.

Exception

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.

For example:

template <class T>
void sink(std::unique_ptr<T> p) {
    // use p ... possibly std::move(p) onward somewhere else
}   // p gets destroyed
Enforcement
  • 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

F.19: For "forward" parameters, pass by TP&& and only std::forward the parameter

Reason

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.

Example
template <class F, class... Args>
inline auto invoke(F f, Args&&... args) {
    return f(forward<Args>(args)...);
}

??? calls ???
Enforcement
  • Flag a function that takes a TP&& parameter (where TP is a template type parameter name) and does anything with it other than std::forwarding it exactly once on every static path.

F.20: For "out" output values, prefer return values to output parameters

Reason

A return value is self-documenting, whereas a & could be either in-out or out-only and is liable to be misused.

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 or similar multi-member type.

Example
// OK: return pointers to elements with the value x
vector<const int*> find_all(const vector<int>&, int x);

// Bad: place pointers to elements with value x in out
void find_all(const vector<int>&, vector<const int*>& out, int x);
Note

A struct of many (individually cheap-to-move) elements may be in aggregate expensive to move.

It is not recommended to return a const value. Such older advice is now obsolete; it does not add value, and it interferes with move semantics.

const vector<int> fct();    // bad: that "const" is more trouble than it is worth

vector<int> g(const vector<int>& vx)
{
    // ...
    f() = vx;   // prevented by the "const"
    // ...
    return f(); // expensive copy: move semantics suppressed by the "const"
}

The argument for adding const to a return value is that it prevents (very rare) accidental access to a temporary. The argument against is prevents (very frequent) use of move semantics.

Exceptions
  • For non-value types, such as types in an inheritance hierarchy, return the object by unique_ptr or shared_ptr.
  • If a type is expensive to move (e.g., array<BigPOD>), consider allocating it on the free store and return a handle (e.g., unique_ptr), or passing it in a reference to non-const target object to fill (to be used as an out-parameter).
  • 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.
Example
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
Enforcement
  • 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.
  • Flag returning a const value. To fix: Remove const to return a non-const value instead.

F.21: To return multiple "out" values, prefer returning a tuple or struct

Reason

A return value is self-documenting as an "output-only" value. Note that C++ does have multiple return values, by convention of using a tuple, possibly with the extra convenience of tie at the call site.

Example
// BAD: output-only parameter documented in a comment
int f(const string& input, /*output only*/ string& output_data)
{
    // ...
    output_data = something();
    return status;
}

// GOOD: self-documenting
tuple<int, string> f(const string& input)
{
    // ...
    return make_tuple(status, something());
}

C++98's standard library already used this style, because a pair is like a two-element tuple. For example, given a set<string> my_set, consider:

// C++98
result = my_set.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:

Sometype iter;                                // default initialize if we haven't already
Someothertype success;                        // used these variables for some other purpose

tie(iter, success) = my_set.insert("Hello");   // normal return value
if (success) do_something_with(iter);

With C++17 we should be able to use "structured bindings" to declare and initialize the multiple variables:

if (auto [ iter, success ] = my_set.insert("Hello"); success) do_something_with(iter);
Exception

Sometimes, we need to pass an object to a function to manipulate its state. In such cases, passing the object by reference T& is usually the right technique. Explicitly passing an in-out parameter back out again as a return value is often not necessary. For example:

istream& operator>>(istream& is, string& s);    // much like std::operator>>()

for (string s; cin >> s; ) {
    // do something with line
}

Here, both s and cin are used as in-out parameters. We pass cin 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.

To compare, if we passed out all values as return values, we would something like this:

pair<istream&, string> get_string(istream& is);  // not recommended
{
    string s;
    cin >> s;
    return {is, s};
}

for (auto p = get_string(cin); p.first; ) {
    // do something with p.second
}

We consider that significantly less elegant and definitely significantly slower.

For a really strict reading this rule (F.21), the exceptions 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.

Note

In many cases it may be useful to return a specific, user-defined "Value or error" type. For example:

struct

The overly-generic pair and tuple should be used only when the value returned represents to independent entities rather than an abstraction.

type along the lines of variant<T, error_code>, rather than using the generic tuple.

Enforcement
  • Output parameters should be replaced by return values. An output parameter is one that the function writes to, invokes a non-const member function, or passes on as a non-const.

F.22: Use T* or owner<T*> to designate a single object

Reason

Readability: it makes the meaning of a plain pointer clear. Enables significant tool support.

Note

In traditional C and C++ code, plain T* is used for many weakly-related purposes, such as:

  • Identify a (single) object (not to be deleted by this function)
  • Point to an object allocated on the free store (and delete it later)
  • 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

This makes it hard to understand what the code does and is supposed to do. It complicates checking and tool support.

Example
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<int>
    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
}

better

void use2(span<int> p, zstring s, owner<int*> q)
{
    p[p.size() - 1] = 666; // OK, a range error can be caught
    cout << s; // OK
    delete q;  // OK
}
Note

owner<T*> represents ownership, zstring represents a C-style string.

Also: Assume that a T* obtained from a smart pointer to T (e.g., unique_ptr<T>) points to a single element.

See also: Support library.

Enforcement
  • (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type.

F.23: Use a not_null<T> to indicate that "null" is not a valid value

Reason

Clarity. A function with a not_null<T> parameter makes it clear that the caller of the function is responsible for any nullptr checks that may be necessary. Similarly, a function with a return value of not_null<T> makes it clear that the caller of the function does not need to check for nullptr.

Example

not_null<T*> makes it obvious to a reader (human or machine) that a test for nullptr is not necessary before dereference. Additionally, when debugging, owner<T*> and not_null<T> can be instrumented to check for correctness.

Consider:

int length(Record* p);

When I call length(p) should I test for p == nullptr first? Should the implementation of length() test for p == nullptr?

// it is the caller's job to make sure p != nullptr
int length(not_null<Record*> p);

// the implementor of length() must assume that p == nullptr is possible
int length(Record* p);
Note

A not_null<T*> is assumed not to be the nullptr; a T* may be the nullptr; both can be represented in memory as a T* (so no run-time overhead is implied).

Note

not_null is not just for built-in pointers. It works for unique_ptr, shared_ptr, and other pointer-like types.

Enforcement
  • (Simple) Warn if a raw pointer is dereferenced without being tested against nullptr (or equivalent) within a function, suggest it is declared not_null instead.
  • (Simple) Error if a raw pointer is sometimes dereferenced after first being tested against nullptr (or equivalent) within the function and sometimes is not.
  • (Simple) Warn if a not_null pointer is tested against nullptr within a function.

F.24: Use a span<T> or a span_p<T> to designate a half-open sequence

Reason

Informal/non-explicit ranges are a source of errors.

Example
X* find(span<X> r, const X& v);    // find v in r

vector<X> vec;
// ...
auto p = find({vec.begin(), vec.end()}, X{});  // find X{} in vec
Note

Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure. In particular, given a pair of arguments (p, n) designating an array [p:p+n), it is in general impossible to know if there really are n elements to access following *p. span<T> and span_p<T> are simple helper classes designating a [p:q) range and a range starting with p and ending with the first element for which a predicate is true, respectively.

Example

A span represents a range of elements, but how do we manipulate elements of that range?

void f(span<int> s)
{
    // range traversal (guaranteed correct)
    for (int x : s) cout << x << '\n';

    // C-style traversal (potentially checked)
    for (int i = 0; i < s.size(); ++i) cout << s[i] << '\n';

    // random access (potentially checked)
    s[7] = 9;

    // extract pointers (potentially checked)
    std::sort(&s[0], &s[s.size() / 2]);
}
Note

A span<T> object does not own its elements and is so small that it can be passed by value.

Passing a span object as an argument is exactly as efficient as passing a pair of pointer arguments or passing a pointer and an integer count.

See also: Support library.

Enforcement

(Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use span instead.

F.25: Use a zstring or a not_null<zstring> to designate a C-style string

Reason

C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters. We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.

Example

Consider:

int length(const char* p);

When I call length(s) should I test for s == nullptr first? Should the implementation of length() test for p == nullptr?

// the implementor of length() must assume that p == nullptr is possible
int length(zstring p);

// it is the caller's job to make sure p != nullptr
int length(not_null<zstring> p);
Note

zstring do not represent ownership.

See also: Support library.

F.26: Use a unique_ptr<T> to transfer ownership where a pointer is needed

Reason

Using unique_ptr is the cheapest way to pass a pointer safely.

Example
unique_ptr<Shape> 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 kCircle:
        return make_unique<Circle>(is);
    case kTriangle:
        return make_unique<Triangle>(is);
    // ...
    }
}
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).

Enforcement

(Simple) Warn if a function returns a locally-allocated raw pointer. Suggest using either unique_ptr or shared_ptr instead.

F.27: Use a shared_ptr<T> to share ownership

Reason

Using std::shared_ptr is the standard way to represent shared ownership. That is, the last owner deletes the object.

Example
shared_ptr<const Image> 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 threads
// last thread to finish deletes the image
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 that pervasive use of shared_ptr has a cost (atomic operations on the shared_ptr's reference count have a measurable aggregate cost).

Alternative

Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.

Enforcement

(Not enforceable) This is a too complex pattern to reliably detect.

F.60: Prefer T* over T& when "no argument" is a valid option

Reason

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
string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
{
    if (p == nullptr) return string{};    // p might be nullptr; remember to check
    return string{p};
}

void print(const vector<int>& r)
{
    // r refers to a vector<int>; no check needed
}
Note

It is possible, but not valid C++ to construct a reference that is essentially a nullptr (e.g., T* p = nullptr; T& r = (T&)*p;). That error is very uncommon.

Note

If you prefer the pointer notation (-> and/or * vs. .), not_null<T*> provides the same guarantee as T&.

Enforcement
  • Flag ???

F.42: Return a T* to indicate a position (only)

Reason

That's what pointers are good for. Returning a T* to transfer ownership is a misuse.

Example
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;
}

If it isn't the nullptr, the pointer returned by find indicates a Node holding s. Importantly, that does not imply a transfer of ownership of the pointed-to object to the caller.

Note

Positions can also be transferred by iterators, indices, and references. A reference is often a superior alternative to a pointer if there is no need to use nullptr or if the object referred to should not change.

Note

Do not return a pointer to something that is not in the caller's scope; see F.43.

See also: discussion of dangling pointer prevention.

Enforcement
  • Flag delete, std::free(), etc. applied to a plain T*. Only owners should be deleted.
  • Flag new, malloc(), etc. assigned to a plain T*. Only owners should be responsible for deletion.

F.43: Never (directly or indirectly) return a pointer or a reference 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 == 999
gx == 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.

  • 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.

Fortunately, most (all?) modern compilers catch and warn against this simple case.

Note

This applies to references as well:

int& f()
{
    int x = 7;
    // ...
    return x;  // Bad: returns reference to object that is about to be destroyed
}
Note

This applies only to non-static local variables. All static variables are (as their name indicates) statically allocated, so that pointers to them cannot dangle.

Example, bad

Not all examples of leaking a pointer to a local variable are that obvious:

int* glob;       // global variables are bad in so many ways

template<class T>
void steal(T x)
{
    glob = x();  // BAD
}

void f()
{
    int i = 99;
    steal([&] { return &i; });
}

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.

Note

The address of a local variable can be "returned"/leaked by a return statement, by a T& out-parameter, as a member of a returned object, as an element of a returned array, and more.

Note

Similar examples can be constructed "leaking" a pointer from an inner scope to an outer one; such examples are handled equivalently to leaks of pointers out of a function.

A slightly different variant of the problem is placing pointers in a container that outlives the objects pointed to.

See also: Another way of getting dangling pointers is pointer invalidation. It can be detected/prevented with similar techniques.

Enforcement
  • Compilers tend to catch return of reference to locals and could in many cases catch return of pointers to locals.
  • Static analysis can catch many common patterns of the use of pointers indicating positions (thus eliminating dangling pointers)

F.44: Return a T& when copy is undesirable and "returning no object" isn't needed

Reason

The language guarantees that a T& refers to an object, so that testing for nullptr isn't necessary.

See also: The return of a reference must not imply transfer of ownership: discussion of dangling pointer prevention and discussion of ownership.

Example
class Car
{
    array<wheel, 4> w;
    // ...
public:
    wheel& get_wheel(size_t i) { Expects(i < 4); return w[i]; }
    // ...
};

void use()
{
    Car c;
    wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c
}
Enforcement

Flag functions where no return expression could yield nullptr

F.45: Don't return a T&&

Reason

It's asking to return a reference to a destroyed temporary object. A && is a magnet for temporary objects. This is fine when the reference to the temporary is being passed "downward" to a callee, because the temporary is guaranteed to outlive the function call. (See F.24 and F.25.) However, it's not fine when passing such a reference "upward" to a larger caller scope. See also ???.

For passthrough functions that pass in parameters (by ordinary reference or by perfect forwarding) and want to return values, use simple auto return type deduction (not auto&&).

Example, bad

If F returns by value, this function returns a reference to a temporary.

template<class F>
auto&& wrapper(F f)
{
    log_call(typeid(f)); // or whatever instrumentation
    return f();
}
Example, good

Better:

template<class F>
auto wrapper(F f)
{
    log_call(typeid(f)); // or whatever instrumentation
    return f();
}
Exception

std::move and std::forward do return &&, but they are just casts -- used by convention only in expression contexts where a reference to a temporary object is passed along within the same expression before the temporary is destroyed. We don't know of any other good examples of returning &&.

Enforcement

Flag any use of && as a return type, except in std::move and std::forward.

F.46: int is the return type for main()

Reason

It's a language rule, but violated through "language extensions" so often that it is worth mentioning. Declaring main (the one global main of a program) void limits portability.

Example
    void main() { /* ... */ };  // bad, not C++

    int main()
    {
        std::cout << "This is the way to do it\n";
    }
Note

We mention this only because of the persistence of this error in the community.

Enforcement
  • The compiler should do it
  • If the compiler doesn't do it, let tools flag it

F.47: Return T& from assignment operators

Reason

The convention for operator overloads (especially on value types) is for operator=(const T&) to perform the assignment and then return (non-const) *this. This ensures consistency with standard library types and follows the principle of "do as the ints do."

Note

Historically there was some guidance to make the assignment operator return const T&. This was primarily to avoid code of the form (a = b) = c -- such code is not common enough to warrant violating consistency with standard types.

Example
class Foo
{
 public:
    ...
    Foo& operator=(const Foo& rhs) {
      // Copy members.
      ...
      return *this;
    }
};
Enforcement

This should be enforced by tooling by checking the return type (and return value) of any assignment operator.

F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)

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.

Example
// 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<work> 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();
Exception

Generic lambdas offer a concise way to write function templates and so can be useful even when a normal function template would do equally well with a little more syntax. This advantage will probably disappear in the future once all functions gain the ability to have Concept parameters.

Enforcement
  • Warn on use of a named non-generic lambda (e.g., auto x = [](int i){ /*...*/; };) that captures nothing and appears at global scope. Write an ordinary function instead.

F.51: Where there is a choice, prefer default arguments over overloading

Reason

Default arguments simply provides alternative interfaces to a single implementation. There is no guarantee that a set of overloaded functions all implement the same semantics. The use of default arguments can avoid code replication.

Note

There is a choice between using default argument and overloading when the alternatives are from a set of arguments of the same types. For example:

void print(const string& s, format f = {});

as opposed to

void print(const string& s);  // use default format
void print(const string& s, format f);

There is not a choice when a set of functions are used to do a semantically equivalent operation to a set of types. For example:

void print(const char&);
void print(int);
void print(zstring);
See also

Default arguments for virtual functions

Enforcement
???

F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms

Reason

For efficiency and correctness, you nearly always want to capture by reference when using the lambda locally. This includes when writing or calling parallel algorithms that are local because they join before returning.

Example

This is a simple three-stage parallel pipeline. Each stage object encapsulates a worker thread and a queue, has a process function to enqueue work, and in its destructor automatically blocks waiting for the queue to empty before ending the thread.

void send_packets(buffers& bufs)
{
    stage encryptor([] (buffer& b){ encrypt(b); });
    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
Enforcement

???

F.53: Avoid capturing by reference in lambdas that will be used nonlocally, including returned, stored on the heap, or passed to another thread

Reason

Pointers and references to locals shouldn't outlive their scope. Lambdas that capture by reference are just another place to store a reference to a local object, and shouldn't do so if they (or a copy) outlive the scope.

Example, bad
int local = 42;

// Want a reference to local.
// Note, that after program exits this scope,
// local no longer exists, therefore
// process() call will have undefined behavior!
thread_pool.queue_work([&]{ process(local); });
Example, good
int local = 42;
// Want a copy of local.
// Since a copy of local is made, it will be
// available at all times for the call.
thread_pool.queue_work([=]{ process(local); });
Enforcement
  • (Simple) Warn when capture-list contains a reference to a locally declared variable
  • (Complex) Flag when capture-list contains a reference to a locally declared variable and the lambda is passed to a non-const and non-local context

F.54: If you capture this, capture all variables explicitly (no default capture)

Reason

It's confusing. Writing [=] in a member function appears to capture by value, but actually captures data members by reference because it actually captures the invisible this pointer by value. If you meant to do that, write this explicitly.

Example
class My_class {
    int x = 0;
    // ...

    void f() {
        int i = 0;
        // ...

        auto lambda = [=]{ use(i, x); };   // BAD: "looks like" copy/value capture
        // [&] has identical semantics and copies the this pointer under the current rules
        // [=,this] and [&,this] are not much better, and confusing

        x = 42;
        lambda(); // calls use(42);
        x = 43;
        lambda(); // calls use(43);

        // ...

        auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing

        // ...
    }
};
Note

This is under active discussion in standardization, and may be addressed in a future version of the standard by adding a new capture mode or possibly adjusting the meaning of [=]. For now, just be explicit.

Enforcement
  • Flag any lambda capture-list that specifies a default capture and also captures this (whether explicitly or via default capture)

C: Classes and Class Hierarchies

A class is a user-defined type, for which a programmer can define the representation, operations, and interfaces. Class hierarchies are used to organize related classes into hierarchical structures.

Class rule summary:

Subsections:

C.1: Organize related data into structures (structs or classes)

Reason

Ease of comprehension. If data is related (for fundamental reasons), that fact should be reflected in code.

Example
void draw(int x, int y, int x2, int y2);  // BAD: unnecessary implicit relationships
void draw(Point from, Point to);          // better
Note

A simple class without virtual functions implies no space or time overhead.

Note

From a language perspective class and struct differ only in the default visibility of their members.

Enforcement

Probably impossible. Maybe a heuristic looking for data items used together is possible.

C.2: Use class if the class has an invariant; use struct if the data members can vary independently

Reason

Readability. Ease of comprehension. The use of class alerts the programmer to the need for an invariant. This is a useful convention.

Note

An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.

If all data members can vary independently of each other, no invariant is possible.

Example
struct Pair {  // the members can vary independently
    string name;
    int volume;
};

but:

class Date {
public:
    // validate that {yy, mm, dd} is a valid date and initialize
    Date(int yy, Month mm, char dd);
    // ...
private:
    int y;
    Month m;
    char d;    // day
};
Note

If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.

Enforcement

Look for structs with all data private and classes with public members.

C.3: Represent the distinction between an interface and an implementation using a class

Reason

An explicit distinction between interface and implementation improves readability and simplifies maintenance.

Example
class Date {
    // ... some representation ...
public:
    Date();
    // validate that {yy, mm, dd} is a valid date and initialize
    Date(int yy, Month mm, char dd);

    int day() const;
    Month month() const;
    // ...
};

For example, we can now change the representation of a Date without affecting its users (recompilation is likely, though).

Note

Using a class in this way to represent the distinction between interface and implementation is of course not the only way. For example, we can use a set of declarations of freestanding functions in a namespace, an abstract base class, or a template function with concepts to represent an interface. The most important issue is to explicitly distinguish between an interface and its implementation "details." Ideally, and typically, an interface is far more stable than its implementation(s).

Enforcement

???

C.4: Make a function a member only if it needs direct access to the representation of a class

Reason

Less coupling than with member functions, fewer functions that can cause trouble by modifying object state, reduces the number of functions that needs to be modified after a change in representation.

Example
class Date {
    // ... relatively small interface ...
};

// helper functions:
Date next_weekday(Date);
bool operator==(Date, Date);

The "helper functions" have no need for direct access to the representation of a Date.

Note

This rule becomes even better if C++ gets "uniform function call".

Enforcement

Look for member function that do not touch data members directly. The snag is that many member functions that do not need to touch data members directly do.

C.5: Place helper functions in the same namespace as the class they support

Reason

A helper function is a function (usually supplied by the writer of a class) that does not need direct access to the representation of the class, yet is seen as part of the useful interface to the class. Placing them in the same namespace as the class makes their relationship to the class obvious and allows them to be found by argument dependent lookup.

Example
namespace Chrono { // here we keep time-related services

    class Time { /* ... */ };
    class Date { /* ... */ };

    // helper functions:
    bool operator==(Date, Date);
    Date next_weekday(Date);
    // ...
}
Note

This is especially important for overloaded operators.

Enforcement
  • Flag global functions taking argument types from a single namespace.

C.7: Don't define a class or enum and declare a variable of its type in the same statement

Reason

Mixing a type definition and the definition of another entity in the same declaration is confusing and unnecessary.

Example; bad
struct Data { /*...*/ } data{ /*...*/ };
Example; good
struct Data { /*...*/ };
Data data{ /*...*/ };
Enforcement
  • Flag if the } of a class or enumeration definition is not followed by a ;. The ; is missing.

C.8: Use class rather than struct if any member is non-public

Reason

Readability. To make it clear that something is being hidden/abstracted. This is a useful convention.

Example, bad
struct Date {
    int d, m;

    Date(int i, Month m);
    // ... lots of functions ...
private:
    int y;  // year
};

There is nothing wrong with this code as far as the C++ language rules are concerned, but nearly everything is wrong from a design perspective. The private data is hidden far from the public data. The data is split in different parts of the class declaration. Different parts of the data have different access. All of this decreases readability and complicates maintenance.

Note

Prefer to place the interface first in a class see.

Enforcement

Flag classes declared with struct if there is a private or public member.

C.9: Minimize exposure of members

Reason

Encapsulation. Information hiding. Minimize the chance of untended access. This simplifies maintenance.

Example
???
Note

Prefer the order public members before protected members before private members see.

Enforcement

Flag protected data.

C.concrete: Concrete types

One ideal for a class is to be a regular type. That means roughly "behaves like an int." A concrete type is the simplest kind of class. 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 used as part of a hierarchy.

Concrete type rule summary:

C.10 Prefer a concrete type over more complicated classes

Reason

A concrete type is fundamentally simpler than a hierarchy: easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster. You need a reason (use cases) for using a hierarchy.

Example
class Point1 {
    int x, y;
    // ... operations ...
    // ... no virtual functions ...
};

class Point2 {
    int x, y;
    // ... operations, some virtual ...
    virtual ~Point2();
};

void use()
{
    Point1 p11 {1, 2};   // make an object on the stack
    Point1 p12 {p11};    // a copy

    auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
    auto p22 = p21.clone();                 // make a copy
    // ...
}

If a class can be part of a hierarchy, we (in real code if not necessarily in small examples) must manipulate its objects through pointers or references. That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.

Note

Concrete types can be stack allocated and be members of other classes.

Note

The use of indirection is fundamental for run-time polymorphic interfaces. The allocation/deallocation overhead is not (that's just the most common case). We can use a base class as the interface of a scoped object of a derived class. This is done where dynamic allocation is prohibited (e.g. hard real-time) and to provide a stable interface to some kinds of plug-ins.

Enforcement

???

C.11: Make concrete types regular

Reason

Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).

Example
struct Bundle {
    string name;
    vector<Record> vr;
};

bool operator==(const Bundle& a, const Bundle& b)
{
    return a.name == b.name && a.vr == b.vr;
}

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!");

In particular, if a concrete type has an assignment also give it an equals operator so that a = b implies a == b.

Enforcement

???

C.ctor: Constructors, assignments, and destructors

These functions control the lifecycle of objects: creation, copy, move, and destruction. Define constructors to guarantee and simplify initialization of classes.

These are default operations:

  • a default constructor: X()
  • a copy constructor: X(const X&)
  • a copy assignment: operator=(const X&)
  • a move constructor: X(X&&)
  • a move assignment: operator=(X&&)
  • a destructor: ~X()

By default, the compiler defines each of these operations if it is used, but the default can be suppressed.

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.

Set of default operations rules:

Destructor rules:

Constructor rules:

Copy and move rules:

Other default operations rules:

C.defop: Default Operations

By default, the language supplies the default operations with their default semantics. However, a programmer can disable or replace these defaults.

C.20: If you can avoid defining default operations, do

Reason

It's the simplest and gives the cleanest semantics.

Example
struct Named_map {
public:
    // ... no default operations declared ...
private:
    string name;
    map<int, int> rep;
};

Named_map nm;        // default construct
Named_map nm2 {nm};  // copy construct

Since std::map and string have all the special functions, no further work is needed.

Note

This is known as "the rule of zero".

Enforcement

(Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule. For example, a class with a (pointer, size) pair of member and a destructor that deletes the pointer could probably be converted to a vector.

C.21: If you define or =delete any default operation, define or =delete them all

Reason

The semantics of the special functions are closely related, so if one needs to be non-default, the odds are that others need modification too.

Example, bad
struct M2 {   // bad: incomplete set of default operations
public:
    // ...
    // ... no copy or move operations ...
    ~M2() { delete[] rep; }
private:
    pair<int, int>* rep;  // zero-terminated set of pairs
};

void use()
{
    M2 x;
    M2 y;
    // ...
    x = y;   // the default assignment
    // ...
}

Given that "special attention" was needed for the destructor (here, to deallocate), the likelihood that copy and move assignment (both will implicitly destroy an object) are correct is low (here, we would get double deletion).

Note

This is known as "the rule of five" or "the rule of six", depending on whether you count the default constructor.

Note

If you want a default implementation of a default operation (while defining another), write =default to show you're doing so intentionally for that function. If you don't want a default operation, suppress it with =delete.

Note

Compilers enforce much of this rule and ideally warn about any violation.

Note

Relying on an implicitly generated copy operation in a class with a destructor is deprecated.

Enforcement

(Simple) A class should have a declaration (even a =delete one) for either all or none of the special functions.

C.22: Make default operations consistent

Reason

The default operations are conceptually a matched set. Their semantics are interrelated. Users will be surprised if copy/move construction and copy/move assignment do logically different things. Users will be surprised if constructors and destructors do not provide a consistent view of resource management. Users will be surprised if copy and move don't reflect the way constructors and destructors work.

Example, bad
class Silly {   // BAD: Inconsistent copy operations
    class Impl {
        // ...
    };
    shared_ptr<Impl> p;
public:
    Silly(const Silly& a) : p{a.p} { *p = *a.p; }   // deep copy
    Silly& operator=(const Silly& a) { p = a.p; }   // shallow copy
    // ...
};

These operations disagree about copy semantics. This will lead to confusion and bugs.

Enforcement
  • (Complex) A copy/move constructor and the corresponding copy/move assignment operator should write to the same member variables at the same level of dereference.
  • (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors.
  • (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable.
  • (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.

C.dtor: Destructors

"Does this class need a destructor?" is a surprisingly powerful design question. For most classes the answer is "no" either because the class holds no resources or because destruction is handled by the rule of 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).

C.30: Define a destructor if a class needs an explicit action at object destruction

Reason

A destructor is implicitly invoked at the end of an object's lifetime. If the default destructor is sufficient, use it. Only define a non-default destructor if a class needs to execute code that is not already part of its members' destructors.

Example
template<typename A>
struct final_action {   // slightly simplified
    A act;
    final_action(A a) :act{a} {}
    ~final_action() { act(); }
};

template<typename A>
final_action<A> finally(A act)   // deduce action type
{
    return final_action<A>{act};
}

void test()
{
    auto act = finally([]{ cout << "Exit test\n"; });  // establish exit action
    // ...
    if (something) return;   // act done here
    // ...
} // act done here

The whole purpose of final_action is to get a piece of code (usually a lambda) executed upon destruction.

Note

There are two general categories of classes that need a user-defined destructor:

  • A class with a resource that is not already represented as a class with a destructor, e.g., a vector or a transaction class.
  • A class that exists primarily to execute an action upon destruction, such as a tracer or final_action.
Example, bad
class Foo {   // bad; use the default destructor
public:
    // ...
    ~Foo() { s = ""; i = 0; vi.clear(); }  // clean up
private:
    string s;
    int i;
    vector<int> vi;
};

The default destructor does it better, more efficiently, and can't get it wrong.

Note

If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use =default.

Enforcement

Look for likely "implicit resources", such as pointers and references. Look for classes with destructors even though all their data members have destructors.

C.31: All resources acquired by a class must be released by the class's destructor

Reason

Prevention of resource leaks, especially in error cases.

Note

For resources represented as classes with a complete set of default operations, this happens automatically.

Example
class X {
    ifstream f;   // may own a file
    // ... no default operations defined or =deleted ...
};

X's ifstream implicitly closes any file it may have open upon destruction of its X.

Example, bad
class X2 {     // bad
    FILE* f;   // may own a file
    // ... no default operations defined or =deleted ...
};

X2 may leak a file handle.

Note

What about a sockets that won't close? A destructor, close, or cleanup operation should never 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. To make the problem worse, many "close/release" operations are not retryable. Many have tried to solve this problem, but no general solution is known. If at all possible, consider failure to close/cleanup a fundamental design error and terminate.

Note

A class can hold pointers and references to objects that it does not own. Obviously, such objects should not be deleted by the class's destructor. For example:

Preprocessor pp { /* ... */ };
Parser p { pp, /* ... */ };
Type_checker tc { p, /* ... */ };

Here p refers to pp but does not own it.

Enforcement
  • (Simple) If a class has pointer or reference member variables that are owners (e.g., deemed owners by using gsl::owner), then they should be referenced in its destructor.
  • (Hard) Determine if pointer or reference member variables are owners when there is no explicit statement of ownership (e.g., look into the constructors).

C.32: If a class has a raw pointer (T*) or reference (T&), consider whether it might be owning

Reason

There is a lot of code that is non-specific about ownership.

Example
???
Note

If the T* or T& is owning, mark it owning. If the T* is not owning, consider marking it ptr. This will aid documentation and analysis.

Enforcement

Look at the initialization of raw member pointers and member references and see if an allocation is used.

C.33: If a class has an owning pointer member, define a destructor

Reason

An owned object must be deleted upon destruction of the object that owns it.

Example

A pointer member may represent a resource. A T* should not do so, but in older code, that's common. Consider a T* a possible owner and therefore suspect.

template<typename T>
class Smart_ptr {
    T* p;   // BAD: vague about ownership of *p
    // ...
public:
    // ... no user-defined default operations ...
};

void use(Smart_ptr<int> p1)
{
    // error: p2.p leaked (if not nullptr and not owned by some other code)
    auto p2 = p1;
}

Note that if you define a destructor, you must define or delete all default operations:

template<typename T>
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!
};

void use(Smart_ptr2<int> p1)
{
    auto p2 = p1;   // error: double deletion
}

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:

template<typename T>
class Smart_ptr3 {
    owner<T*> p;   // OK: explicit about ownership of *p
    // ...
public:
    // ...
    // ... copy and move operations ...
    ~Smart_ptr3() { delete p; }
};

void use(Smart_ptr3<int> p1)
{
    auto p2 = p1;   // error: double deletion
}
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.

Enforcement
  • A class with a pointer data member is suspect.
  • A class with an owner<T> should define its default operations.

C.34: If a class has an owning reference member, define a destructor

Reason

A reference member may represent a resource. It should not do so, but in older code, that's common. See pointer members and destructors. Also, copying may lead to slicing.

Example, bad
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} { /* ... */ }
    // ...
};

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.

Example
class Handle {        // OK
    owner<Shape&> s;  // use reference rather than pointer to prevent rebinding
    // ...
public:
    Handle(Shape& ss) : s{ss} { /* ... */ }
    ~Handle() { delete &s; }
    // ...
};

Independently of whether Handle owns its Shape, we must consider the default copy operations suspect:

// the Handle had better own the Circle or we have a leak
Handle x {*new Circle{p1, 17}};

Handle y {*new Triangle{p1, p2, p3}};
x = y;     // the default assignment will try *x.s = *y.s

That x = y is highly suspect. Assigning a Triangle to a Circle? Unless Shape has its copy assignment =deleted, only the Shape part of Triangle is copied into the Circle.

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.

Enforcement
  • A class with a reference data member is suspect.
  • A class with an owner<T> reference should define its default operations.

C.35: A base class destructor should be either public and virtual, or protected and nonvirtual

Reason

To prevent undefined behavior. If the destructor is public, then calling code can attempt to destroy a derived class object through a base class pointer, and the result is undefined if the base class's destructor is non-virtual. If the destructor is protected, then calling code cannot destroy through a base class pointer and the destructor does not need to be virtual; it does need to be protected, not private, so that derived destructors can invoke it. In general, the writer of a base class does not know the appropriate action to be done upon destruction.

Discussion

See this in the Discussion section.

Example, bad
struct Base {  // BAD: no virtual destructor
    virtual void f();
};

struct D : Base {
    string s {"a resource needing cleanup"};
    ~D() { /* ... do some cleanup ... */ }
    // ...
};

void use()
{
    unique_ptr<Base> p = make_unique<D>();
    // ...
} // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
Note

A virtual function defines an interface to derived classes that can be used without looking at the derived classes. If the interface allows destroying, it should be safe to do so.

Note

A destructor must be nonprivate or it will prevent using the type :

class X {
    ~X();   // private destructor
    // ...
};

void use()
{
    X a;                        // error: cannot destroy
    auto p = make_unique<X>();  // error: cannot destroy
}
Exception

We can imagine one case where you could want a protected virtual destructor: When an object of a derived type (and only of such a type) should be allowed to destroy another object (not itself) through a pointer to base. We haven't seen such a case in practice, though.

Enforcement
  • A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.

C.36: A destructor may not fail

Reason

In general we do not know how to write error-free code if a destructor should fail. The standard library requires that all classes it deals with have destructors that do not exit by throwing.

Example
class X {
public:
    ~X() noexcept;
    // ...
};

X::~X() noexcept
{
    // ...
    if (cannot_release_a_resource) terminate();
    // ...
}
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 a real practical problem: For example, what about a socket 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.

Note

Declare a destructor noexcept. That will ensure that it either completes normally or terminate the program.

Note

If a resource cannot be released and the program may not fail, try to signal the failure to the rest of the system somehow (maybe even by modifying some global state and hope something will notice and be able to take care of the problem). Be fully aware that this technique is special-purpose and error-prone. Consider the "my connection will not close" example. Probably there is a problem at the other end of the connection and only a piece of code responsible for both ends of the connection can properly handle the problem. The destructor could send a message (somehow) to the responsible part of the system, consider that to have closed the connection, and return normally.

Note

If a destructor uses operations that may fail, it can catch exceptions and in some cases still complete successfully (e.g., by using a different clean-up mechanism from the one that threw an exception).

Enforcement

(Simple) A destructor should be declared noexcept.

C.37: Make destructors noexcept

Reason

A destructor may not fail. If a destructor tries to exit with an exception, it's a bad design error and the program had better terminate.

Note

A destructor (either user-defined or compiler-generated) is implicitly declared noexcept (independently of what code is in its body) if all of the members of its class have noexcept destructors.

Enforcement

(Simple) A destructor should be declared noexcept.

C.ctor: Constructors

A constructor defines how an object is initialized (constructed).

C.40: Define a constructor if a class has an invariant

Reason

That's what constructors are for.

Example
class Date {  // a Date represents a valid date
              // in the January 1, 1900 to December 31, 2100 range
    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;
};

It is often a good idea to express the invariant as an Ensures on the constructor.

Note

A constructor can be used for convenience even if a class does not have an invariant. For example:

struct Rec {
    string s;
    int i {0};
    Rec(const string& ss) : s{ss} {}
    Rec(int ii) :i{ii} {}
};

Rec r1 {7};
Rec r2 {"Foo bar"};
Note

The C++11 initializer list rule eliminates the need for many constructors. For example:

struct Rec2{
    string s;
    int i;
    Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {}   // redundant
};

Rec2 r1 {"Foo", 7};
Rec2 r2 {"Bar"};

The Rec2 constructor is redundant. Also, the default for int would be better done as a member initializer.

See also: construct valid object and constructor throws.

Enforcement
  • Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant)

C.41: A constructor should create a fully initialized object

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.

Example, bad
class X1 {
    FILE* f;   // call init() before any other function
    // ...
public:
    X1() {}
    void init();   // initialize f
    void read();   // read from f
    // ...
};

void f()
{
    X1 file;
    file.read();   // crash or bad read!
    // ...
    file.init();   // too late
    // ...
}

Compilers do not read comments.

Exception

If a valid object cannot conveniently be constructed by a constructor, use a factory function.

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

If a constructor acquires a resource (to create a valid object), that resource should be released by the destructor. The idiom of having constructors acquire resources and destructors release them is called RAII ("Resource Acquisition 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 function
    // ...
public:
    X2(const string& name)
        :f{fopen(name.c_str(), "r")}
    {
        if (f == nullptr) throw runtime_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 function
    bool valid;
    // ...
public:
    X3(const string& name)
        :f{fopen(name.c_str(), "r")}, valid{false}
    {
        if (f) valid = true;
        // ...
    }

    bool is_valid() { return valid; }
    void read();   // read from f
    // ...
};

void f()
{
    X3 file {"Heraclides"};
    file.read();   // crash or bad read!
    // ...
    if (file.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 and relying on users to consistently check an is_valid() function before use is tedious, error-prone, and inefficient.

Exception

There are domains, such as some hard-real-time systems (think airplane controls) where (without additional tool support) exception handling is not sufficiently predictable from a timing perspective. There the is_valid() technique must be used. In such cases, check is_valid() consistently and immediately to simulate RAII.

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.

Note

One reason people have used init() functions rather than doing the initialization work in a constructor has been to avoid code replication. Delegating constructors and default member initialization do that better. Another reason is been to delay initialization until an object is needed; the solution to that is often not to declare a variable until it can be properly initialized

Enforcement

C.43: Ensure that a class has a default constructor

Reason

Many language and library facilities rely on default constructors to initialize their elements, e.g. T a[10] and std::vector<T> v(10).

Example , bad
class Date { // BAD: no default constructor
public:
    Date(int dd, int mm, int yyyy);
    // ...
};

vector<Date> vd1(1000);   // default Date needed here
vector<Date> vd2(1000, Date{Month::october, 7, 1885});   // alternative

The default constructor is only auto-generated if there is no user-declared constructor, hence it's impossible to initialize the vector vd1 in the example above.

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 have a "first date" (e.g. January 1, 1970 is popular), so making that the default is usually trivial.

Example
class Date {
public:
    Date(int dd, int mm, int yyyy);
    Date() = default; // See also C.45
    // ...
private:
    int dd = 1;
    int mm = 1;
    int yyyy = 1970;
    // ...
};

vector<Date> vd1(1000);
Note

A class with members that all have default constructors implicitly gets a default constructor:

struct X {
    string s;
    vector<int> v;
};

X x; // means X{{}, {}}; that is the empty string and the empty vector

Beware that built-in types are not properly default constructed:

struct X {
    string s;
    int i;
};

void f()
{
    X x;    // x.s is initialized to the empty string; x.i is uninitialized

    cout << x.s << ' ' << x.i << '\n';
    ++x.i;
}

Statically allocated objects of built-in types are by default initialized to 0, but local built-in variables are not. Beware that your compiler may default initialize local built-in variables, whereas an optimized build will not. Thus, code like the example above may appear to work, but it relies on undefined behavior. Assuming that you want initialization, an explicit default initialization can help:

struct X {
    string s;
    int i {};   // default initialize (to 0)
};
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<typename T>
// elem points to space-elem element allocated using new
class Vector0 {
public:
    Vector0() :Vector0{0} {}
    Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
    // ...
private:
    own<T*> 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<typename T>
// elem is nullptr or elem points to space-elem element allocated using new
class Vector1 {
public:
    // sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
    Vector1() noexcept {}
    Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
    // ...
private:
    own<T*> 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.

Enforcement
  • Flag throwing default constructors

C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead

Reason

Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.

Example, bad
class X1 { // BAD: doesn't use member initializers
    string s;
    int i;
public:
    X1() :s{"default"}, i{1} { }
    // ...
};
Example
class X2 {
    string s = "default";
    int i = 1;
public:
    // use compiler-generated default constructor
    // ...
};
Enforcement

(Simple) A default constructor should do more than just initialize member variables with constants.

C.46: By default, declare single-argument constructors explicit

Reason

To avoid unintended conversions.

Example, bad
class String {
    // ...
public:
    String(int);   // BAD
    // ...
};

String s = 10;   // surprise: string of size 10
Exception

If you really want an implicit conversion from the constructor argument type to the class type, don't use explicit:

class Complex {
    // ...
public:
    Complex(double d);   // OK: we want a conversion from d to {d, 0}
    // ...
};

Complex z = 10.7;   // unsurprising conversion

See also: Discussion of implicit conversions.

Enforcement

(Simple) Single-argument constructors should be declared explicit. Good single argument non-explicit constructors are rare in most code based. Warn for all that are not on a "positive list".

C.47: Define and initialize member variables in the order of member declaration

Reason

To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).

Example, bad
class Foo {
    int m1;
    int m2;
public:
    Foo(int x) :m2{x}, m1{++x} { }   // BAD: misleading initializer order
    // ...
};

Foo x(1); // surprise: x.m1 == x.m2 == 2
Enforcement

(Simple) A member initializer list should mention the members in the same order they are declared.

See also: Discussion

C.48: Prefer in-class initializers to member initializers in constructors for constant initializers

Reason

Makes it explicit that the same value is expected to be used in all constructors. Avoids repetition. Avoids maintenance problems. It leads to the shortest and most efficient code.

Example, bad
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
    // ...
};

How would a maintainer know whether j was deliberately uninitialized (probably a poor idea anyway) and whether it was intentional to give s the default value "" in one case and qqq in another (almost certainly a bug)? The problem with j (forgetting to initialize a member) often happens when a new member is added to an existing class.

Example
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
    // ...
};

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:

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
    // ...
};
Enforcement
  • (Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
  • (Simple) Default arguments to constructors suggest an in-class initializer may be more appropriate.

C.49: Prefer initialization to assignment in constructors

Reason

An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.

Example, good
class A {   // Good
    string s1;
public:
    A() : s1{"Hello, "} { }    // GOOD: directly construct
    // ...
};
Example, bad
class B {   // BAD
    string s1;
public:
    B() { s1 = "Hello, "; }   // BAD: default constructor followed by assignment
    // ...
};

class C {   // UGLY, aka very bad
    int* p;
public:
    C() { cout << *p; p = new int{10}; }   // accidental use before initialized
    // ...
};

C.50: Use a factory function if you need "virtual behavior" during initialization

Reason

If the state of a base class object must depend on the state of a derived part of the object, we need to use a virtual function (or equivalent) while minimizing the window of opportunity to misuse an imperfectly constructed object.

Example, bad
class B {
public:
    B()
    {
        // ...
        f();   // BAD: virtual call in constructor
        // ...
    }

    virtual void f() = 0;

    // ...
};
Example
class B {
protected:
    B() { /* ... */ }              // create an imperfectly initialized object

    virtual void PostInitialize()  // to be called right after construction
    {
        // ...
        f();    // GOOD: virtual dispatch is safe
        // ...
    }

public:
    virtual void f() = 0;

    template<class T>
    static shared_ptr<T> Create()  // interface for creating objects
    {
        auto p = make_shared<T>();
        p->PostInitialize();
        return p;
    }
};

class D : public B { /* ... */ };            // some derived class

shared_ptr<D> p = D::Create<D>();  // creating a D object

By making the constructor protected we avoid an incompletely constructed object escaping into the wild. By providing the factory function Create(), we make construction (on the free store) convenient.

Note

Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.

See also: Discussion

C.51: Use delegating constructors to represent common actions for all constructors of a class

Reason

To avoid repetition and accidental differences.

Example, bad
class Date {   // BAD: repetitive
    int d;
    Month m;
    int y;
public:
    Date(int ii, Month mm, year yy)
        :i{ii}, m{mm}, y{yy}
        { if (!valid(i, m, y)) throw Bad_date{}; }

    Date(int ii, Month mm)
        :i{ii}, m{mm} y{current_year()}
        { if (!valid(i, m, y)) throw Bad_date{}; }
    // ...
};

The common action gets tedious to write and may accidentally not be common.

Example
class Date2 {
    int d;
    Month m;
    int y;
public:
    Date2(int ii, Month mm, year yy)
        :i{ii}, m{mm}, y{yy}
        { if (!valid(i, m, y)) throw Bad_date{}; }

    Date2(int ii, Month mm)
        :Date2{ii, mm, current_year()} {}
    // ...
};

See also: If the "repeated action" is a simple initialization, consider an in-class member initializer.

Enforcement

(Moderate) Look for similar constructor bodies.

C.52: Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization

Reason

If you need those constructors for a derived class, re-implementing them is tedious and error prone.

Example

std::vector has a lot of tricky constructors, so if I want my own vector, I don't want to reimplement them:

class Rec {
    // ... data and lots of nice constructors ...
};

class Oper : public Rec {
    using Rec::Rec;
    // ... no data members ...
    // ... lots of nice utility functions ...
};
Example, bad
struct Rec2 : public Rec {
    int x;
    using Rec::Rec;
};

Rec2 r {"foo", 7};
int val = r.x;   // uninitialized
Enforcement

Make sure that every member of the derived class is initialized.

C.copy: Copy and move

Value types should generally be copyable, but interfaces in a class hierarchy should not. Resource handles may or may not be copyable. Types can be defined to move for logical as well as performance reasons.

C.60: Make copy assignment non-virtual, take the parameter by const&, and return by non-const&

Reason

It is simple and efficient. If you want to optimize for rvalues, provide an overload that takes a && (see F.24).

Example
class Foo {
public:
    Foo& operator=(const Foo& x)
    {
        // GOOD: no need to check for self-assignment (other than performance)
        auto tmp = x;
        std::swap(*this, tmp);
        return *this;
    }
    // ...
};

Foo a;
Foo b;
Foo f();

a = b;    // assign lvalue: copy
a = f();  // assign rvalue: potentially move
Note

The swap implementation technique offers the strong guarantee.

Example

But what if you can get significantly better performance by not making a temporary copy? Consider a simple Vector intended for a domain where assignment of large, equal-sized Vectors is common. In this case, the copy of elements implied by the swap implementation technique could cause an order of magnitude increase in cost:

template<typename T>
class Vector {
public:
    Vector& operator=(const Vector&);
    // ...
private:
    T* elem;
    int sz;
};

Vector& Vector::operator=(const Vector& a)
{
    if (a.sz > sz) {
        // ... use the swap technique, it can't be bettered ...
        return *this
    }
    // ... copy sz elements from *a.elem to elem ...
    if (a.sz < sz) {
        // ... destroy the surplus elements in *this* and adjust size ...
    }
    return *this;
}

By writing directly to the target elements, we will get only the basic guarantee rather than the strong guarantee offered by the swap technique. Beware of self assignment.

Alternatives: If you think you need a virtual assignment operator, and understand why that's deeply problematic, don't call it operator=. Make it a named function like virtual void assign(const Foo&). See copy constructor vs. clone().

Enforcement
  • (Simple) An assignment operator should not be virtual. Here be dragons!
  • (Simple) An assignment operator should return T& to enable chaining, not alternatives like const T& which interfere with composability and putting objects in containers.
  • (Moderate) An assignment operator should (implicitly or explicitly) invoke all base and member assignment operators. Look at the destructor to determine if the type has pointer semantics or value semantics.

C.61: A copy operation should copy

Reason

That is the generally assumed semantics. After x = y, we should have x == y. After a copy x and y can be independent objects (value semantics, the way non-pointer built-in types and the standard-library types work) or refer to a shared object (pointer semantics, the way pointers work).

Example
class X {   // OK: value semantics
public:
    X();
    X(const X&);     // copy X
    void modify();   // change the value of X
    // ...
    ~X() { delete[] p; }
private:
    T* p;
    int sz;
};

bool operator==(const X& a, const X& b)
{
    return a.sz == b.sz && equal(a.p, a.p + a.sz, b.p, b.p + b.sz);
}

X::X(const X& a)
    :p{new T[a.sz]}, sz{a.sz}
{
    copy(a.p, a.p + sz, a.p);
}

X x;
X y = x;
if (x != y) throw Bad{};
x.modify();
if (x == y) throw Bad{};   // assume value semantics
Example
class X2 {  // OK: pointer semantics
public:
    X2();
    X2(const X&) = default; // shallow copy
    ~X2() = default;
    void modify();          // change the value of X
    // ...
private:
    T* p;
    int sz;
};

bool operator==(const X2& a, const X2& b)
{
    return a.sz == b.sz && a.p == b.p;
}

X2 x;
X2 y = x;
if (x != y) throw Bad{};
x.modify();
if (x != y) throw Bad{};  // assume pointer semantics
Note

Prefer copy semantics unless you are building a "smart pointer". Value semantics is the simplest to reason about and what the standard library facilities expect.

Enforcement

(Not enforceable)

C.62: Make copy assignment safe for self-assignment

Reason

If x = x changes the value of x, people will be surprised and bad errors will occur (often including leaks).

Example

The standard-library containers handle self-assignment elegantly and efficiently:

std::vector<int> v = {3, 1, 4, 1, 5, 9};
v = v;
// the value of v is still {3, 1, 4, 1, 5, 9}
Note

The default assignment generated from members that handle self-assignment correctly handles self-assignment.

struct Bar {
    vector<pair<int, int>> v;
    map<string, int> m;
    string s;
};

Bar b;
// ...
b = b;   // correct and efficient
Note

You can handle self-assignment by explicitly testing for self-assignment, but often it is faster and more elegant to cope without such a test (e.g., using swap).

class Foo {
    string s;
    int i;
public:
    Foo& operator=(const Foo& a);
    // ...
};

Foo& Foo::operator=(const Foo& a)   // OK, but there is a cost
{
    if (this == &a) return *this;
    s = a.s;
    i = a.i;
    return *this;
}

This is obviously safe and apparently efficient. However, what if we do one self-assignment per million assignments? That's about a million redundant tests (but since the answer is essentially always the same, the computer's branch predictor will guess right essentially every time). Consider:

Foo& Foo::operator=(const Foo& a)   // simpler, and probably much better
{
    s = a.s;
    i = a.i;
    return *this;
}

std::string is safe for self-assignment and so are int. All the cost is carried by the (rare) case of self-assignment.

Enforcement

(Simple) Assignment operators should not contain the pattern if (this == &a) return *this; ???

C.63: Make move assignment non-virtual, take the parameter by &&, and return by non-const &

Reason

It is simple and efficient.

See: The rule for copy-assignment.

Enforcement

Equivalent to what is done for copy-assignment.

  • (Simple) An assignment operator should not be virtual. Here be dragons!
  • (Simple) An assignment operator should return T& to enable chaining, not alternatives like const T& which interfere with composability and putting objects in containers.
  • (Moderate) A move assignment operator should (implicitly or explicitly) invoke all base and member move assignment operators.

C.64: A move operation should move and leave its source in a valid state

Reason

That is the generally assumed semantics. After y = std::move(x) the value of y should be the value x had and x should be in a valid state.

Example
template<typename T>
class X {   // OK: value semantics
public:
    X();
    X(X&& a);          // move X
    void modify();     // change the value of X
    // ...
    ~X() { delete[] p; }
private:
    T* p;
    int sz;
};


X::X(X&& a)
    :p{a.p}, sz{a.sz}  // steal representation
{
    a.p = nullptr;     // set to "empty"
    a.sz = 0;
}

void use()
{
    X x{};
    // ...
    X y = std::move(x);
    x = X{};   // OK
} // OK: x can be destroyed
Note

Ideally, that moved-from should be the default value of the type. Ensure that unless there is an exceptionally good reason not to. However, not all types have a default value and for some types establishing the default value can be expensive. The standard requires only that the moved-from object can be destroyed. Often, we can easily and cheaply do better: The standard library assumes that it it possible to assign to a moved-from object. Always leave the moved-from object in some (necessarily specified) valid state.

Note

Unless there is an exceptionally strong reason not to, make x = std::move(y); y = z; work with the conventional semantics.

Enforcement

(Not enforceable) Look for assignments to members in the move operation. If there is a default constructor, compare those assignments to the initializations in the default constructor.

C.65: Make move assignment safe for self-assignment

Reason

If x = x changes the value of x, people will be surprised and bad errors may occur. However, people don't usually directly write a self-assignment that turn into a move, but it can occur. However, std::swap is implemented using move operations so if you accidentally do swap(a, b) where a and b refer to the same object, failing to handle self-move could be a serious and subtle error.

Example
class Foo {
    string s;
    int i;
public:
    Foo& operator=(Foo&& a);
    // ...
};

Foo& Foo::operator=(Foo&& a)       // OK, but there is a cost
{
    if (this == &a) return *this;  // this line is redundant
    s = std::move(a.s);
    i = a.i;
    return *this;
}

The one-in-a-million argument against if (this == &a) return *this; tests from the discussion of self-assignment is even more relevant for self-move.

Note

There is no know general way of avoiding a if (this == &a) return *this; test for a move assignment and still get a correct answer (i.e., after x = x the value of x is unchanged).

Note

The ISO standard guarantees only a "valid but unspecified" state for the standard library containers. Apparently this has not been a problem in about 10 years of experimental and production use. Please contact the editors if you find a counter example. The rule here is more caution and insists on complete safety.

Example

Here is a way to move a pointer without a test (imagine it as code in the implementation a move assignment):

// move from other.ptr to this->ptr
T* temp = other.ptr;
other.ptr = nullptr;
delete ptr;
ptr = temp;
Enforcement
  • (Moderate) In the case of self-assignment, a move assignment operator should not leave the object holding pointer members that have been deleted or set to nullptr.
  • (Not enforceable) Look at the use of standard-library container types (incl. string) and consider them safe for ordinary (not life-critical) uses.

C.66: Make move operations noexcept

Reason

A throwing move violates most people's reasonably assumptions. A non-throwing move will be used more efficiently by standard-library and language facilities.

Example
template<typename T>
class Vector {
    // ...
    Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.sz = 0; a.elem = nullptr; }
    Vector& operator=(Vector&& a) noexcept { elem = a.elem; sz = a.sz; a.sz = 0; a.elem = nullptr; }
    // ...
public:
    T* elem;
    int sz;
};

These copy operations do not throw.

Example, bad
template<typename T>
class Vector2 {
    // ...
    Vector2(Vector2&& a) { *this = a; }             // just use the copy
    Vector2& operator=(Vector2&& a) { *this = a; }  // just use the copy
    // ...
public:
    T* elem;
    int sz;
};

This Vector2 is not just inefficient, but since a vector copy requires allocation, it can throw.

Enforcement

(Simple) A move operation should be marked noexcept.

C.67: A base class should suppress copying, and provide a virtual clone instead if "copying" is desired

Reason

To prevent slicing, because the normal copy operations will copy only the base portion of a derived object.

Example, bad
class B { // BAD: base class doesn't suppress copying
    int data;
    // ... nothing about copy operations, so uses default ...
};

class D : public B {
    string more_data; // add a data member
    // ...
};

auto d = make_unique<D>();

// oops, slices the object; gets only d.data but drops d.more_data
auto b = make_unique<B>(d);
Example
class B { // GOOD: base class suppresses copying
    B(const B&) = delete;
    B& operator=(const B&) = delete;
    virtual unique_ptr<B> clone() { return /* B object */; }
    // ...
};

class D : public B {
    string more_data; // add a data member
    unique_ptr<B> clone() override { return /* D object */; }
    // ...
};

auto d = make_unique<D>();
auto b = d.clone(); // ok, deep clone
Note

It's good to return a smart pointer, but unlike with raw pointers the return type cannot be covariant (for example, D::clone can't return a unique_ptr<D>. Don't let this tempt you into returning an owning raw pointer; this is a minor drawback compared to the major robustness benefit delivered by the owning smart pointer.

Exception

If you need covariant return types, return an owner<derived*>. See C.130.

Enforcement

A class with any virtual function should not have a copy constructor or copy assignment operator (compiler-generated or handwritten).

C.other: Other default operation rules

In addition to the operations for which the language offer default implementations, there are a few operations that are so foundational that it rules for their definition are needed: comparisons, swap, and hash.

C.80: Use =default if you have to be explicit about using the default semantics

Reason

The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.

Example
class Tracer {
    string message;
public:
    Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
    ~Tracer() { cerr << "exiting " << message << '\n'; }

    Tracer(const Tracer&) = default;
    Tracer& operator=(const Tracer&) = default;
    Tracer(Tracer&&) = default;
    Tracer& operator=(Tracer&&) = default;
};

Because we defined the destructor, we must define the copy and move operations. The = default is the best and simplest way of doing that.

Example, bad
class Tracer2 {
    string message;
public:
    Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
    ~Tracer2() { cerr << "exiting " << message << '\n'; }

    Tracer2(const Tracer2& a) : message{a.message} {}
    Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
    Tracer2(Tracer2&& a) :message{a.message} {}
    Tracer2& operator=(Tracer2&& a) { message = a.message; return *this; }
};

Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.

Enforcement

(Moderate) The body of a special operation should not have the same accessibility and semantics as the compiler-generated version, because that would be redundant

C.81: Use =delete when you want to disable default behavior (without wanting an alternative)

Reason

In a few cases, a default operation is not desirable.

Example
class Immortal {
public:
    ~Immortal() = delete;   // do not allow destruction
    // ...
};

void use()
{
    Immortal ugh;   // error: ugh cannot be destroyed
    Immortal* p = new Immortal{};
    delete p;       // error: cannot destroy *p
}
Example

A unique_ptr can be moved, but not copied. To achieve that its copy operations are deleted. To avoid copying it is necessary to =delete its copy operations from lvalues:

template <class T, class D = default_delete<T>> class unique_ptr {
public:
    // ...
    constexpr unique_ptr() noexcept;
    explicit unique_ptr(pointer p) noexcept;
    // ...
    unique_ptr(unique_ptr&& u) noexcept;   // move constructor
    // ...
    unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
    // ...
};

unique_ptr<int> make();   // make "something" and return it by moving

void f()
{
    unique_ptr<int> pi {};
    auto pi2 {pi};      // error: no move constructor from lvalue
    auto pi3 {make()};  // OK, move: the result of make() is an rvalue
}
Enforcement

The elimination of a default operation is (should be) based on the desired semantics of the class. Consider such classes suspect, but maintain a "positive list" of classes where a human has asserted that the semantics is correct.

C.82: Don't call virtual functions in constructors and destructors

Reason

The function called will be that of the object constructed so far, rather than a possibly overriding function in a derived class. This can be most confusing. Worse, a direct or indirect call to an unimplemented pure virtual function from a constructor or destructor results in undefined behavior.

Example, bad
class Base {
public:
    virtual void f() = 0;   // not implemented
    virtual void g();       // implemented with Base version
    virtual void h();       // implemented with Base version
};

class Derived : public Base {
public:
    void g() override;   // provide Derived implementation
    void h() final;      // provide Derived implementation

    Derived()
    {
        // BAD: attempt to call an unimplemented virtual function
        f();

        // BAD: will call Derived::g, not dispatch further virtually
        g();

        // GOOD: explicitly state intent to call only the visible version
        Derived::g();

        // ok, no qualification needed, h is final
        h();
    }
};

Note that calling a specific explicitly qualified function is not a virtual call even if the function is virtual.

See also factory functions for how to achieve the effect of a call to a derived class function without risking undefined behavior.

Note

There is nothing inherently wrong with calling virtual functions from constructors and destructors. The semantics of such calls is type safe. However, experience shows that such calls are rarely needed, easily confuse maintainers, and become a source of errors when used by novices.

Enforcement
  • Flag calls of virtual functions from constructors and destructors.

C.83: For value-like types, consider providing a noexcept swap function

Reason

A swap can be handy for implementing a number of idioms, from smoothly moving objects around to implementing assignment easily to providing a guaranteed commit function that enables strongly error-safe calling code. Consider using swap to implement copy assignment in terms of copy construction. See also destructors, deallocation, and swap must never fail.

Example, good
class Foo {
    // ...
public:
    void swap(Foo& rhs) noexcept
    {
        m1.swap(rhs.m1);
        std::swap(m2, rhs.m2);
    }
private:
    Bar m1;
    int m2;
};

Providing a nonmember swap function in the same namespace as your type for callers' convenience.

void swap(Foo& a, Foo& b)
{
    a.swap(b);
}
Enforcement
  • (Simple) A class without virtual functions should have a swap member function declared.
  • (Simple) When a class has a swap member function, it should be declared noexcept.

C.84: A swap function may not fail

Reason

swap is widely used in ways that are assumed never to fail and programs cannot easily be written to work correctly in the presence of a failing swap. The standard-library containers and algorithms will not work correctly if a swap of an element type fails.

Example, bad
void swap(My_vector& x, My_vector& y)
{
    auto tmp = x;   // copy elements
    x = y;
    y = tmp;
}

This is not just slow, but if a memory allocation occurs for the elements in tmp, this swap may throw and would make STL algorithms fail if used with them.

Enforcement

(Simple) When a class has a swap member function, it should be declared noexcept.

C.85: Make swap noexcept

Reason

A swap may not fail. If a swap tries to exit with an exception, it's a bad design error and the program had better terminate.

Enforcement

(Simple) When a class has a swap member function, it should be declared noexcept.

C.86: Make == symmetric with respect to operand types and noexcept

Reason

Asymmetric treatment of operands is surprising and a source of errors where conversions are possible. == is a fundamental operations and programmers should be able to use it without fear of failure.

Example
class X {
    string name;
    int number;
};

bool operator==(const X& a, const X& b) noexcept {
    return a.name == b.name && a.number == b.number;
}
Example, bad
class B {
    string name;
    int number;
    bool operator==(const B& a) const {
        return name == a.name && number == a.number;
    }
    // ...
};

B's comparison accepts conversions for its second operand, but not its first.

Note

If a class has a failure state, like double's NaN, there is a temptation to make a comparison against the failure state throw. The alternative is to make two failure states compare equal and any valid state compare false against the failure state.

Note

This rule applies to all the usual comparison operators: !=, <, <=, >, and >=.

Enforcement
  • Flag an operator==() for which the argument types differ; same for other comparison operators: !=, <, <=, >, and >=.
  • Flag member operator==()s; same for other comparison operators: !=, <, <=, >, and >=.

C.87: Beware of == on base classes

Reason

It is really hard to write a foolproof and useful == for a hierarchy.

Example, bad
class B {
    string name;
    int number;
    virtual bool operator==(const B& a) const
    {
         return name == a.name && number == a.number;
    }
    // ...
};

B's comparison accepts conversions for its second operand, but not its first.

class D :B {
    char character;
    virtual bool operator==(const D& a) const
    {
        return name == a.name && number == a.number && character == a.character;
    }
    // ...
};

B b = ...
D d = ...
b == d;    // compares name and number, ignores d's character
d == b;    // error: no == defined
D d2;
d == d2;   // compares name, number, and character
B& b2 = d2;
b2 == d;   // compares name and number, ignores d2's and d's character

Of course there are ways of making == work in a hierarchy, but the naive approaches do not scale

Note

This rule applies to all the usual comparison operators: !=, <, <=, >, and >=.

Enforcement
  • Flag a virtual operator==(); same for other comparison operators: !=, <, <=, >, and >=.

C.89: Make a hash noexcept

Reason

Users of hashed containers use hash indirectly and don't expect simple access to throw. It's a standard-library requirement.

Example, bad
template<>
struct hash<My_type> {  // thoroughly bad hash specialization
    using result_type = size_t;
    using argument_type = My_type;

    size_t operator() (const My_type & x) const
    {
        size_t xs = x.s.size();
        if (xs < 4) throw Bad_My_type{};    // "Nobody expects the Spanish inquisition!"
        return hash<size_t>()(x.s.size()) ^ trim(x.s);
    }
};

int main()
{
    unordered_map<My_type, int> m;
    My_type mt{ "asdfg" };
    m[mt] = 7;
    cout << m[My_type{ "asdfg" }] << '\n';
}

If you have to define a hash specialization, try simply to let it combine standard-library hash specializations with ^ (xor). That tends to work better than "cleverness" for non-specialists.

Enforcement
  • Flag throwing hashes.

C.con: Containers and other resource handles

A container is an object holding a sequence of objects of some type; std::vector is the archetypical container. A resource handle is a class that owns a resource; std::vector is the typical resource handle; its resource is its sequence of elements.

Summary of container rules:

See also: Resources

C.lambdas: Function objects and lambdas

A function object is an object supplying an overloaded () so that you can call it. A lambda expression (colloquially often shortened to "a lambda") is a notation for generating a function object. Function objects should be cheap to copy (and therefore passed by value).

Summary:

C.hier: Class hierarchies (OOP)

A class hierarchy is constructed to represent a set of hierarchically organized concepts (only). Typically base classes act as interfaces. There are two major uses for hierarchies, often named implementation inheritance and interface inheritance.

Class hierarchy rule summary:

Designing rules for classes in a hierarchy summary:

Accessing objects in a hierarchy rule summary:

C.120: Use class hierarchies to represent concepts with inherent hierarchical structure (only)

Reason

Direct representation of ideas in code eases comprehension and maintenance. Make sure the idea represented in the base class exactly matches all derived types and there is not a better way to express it than using the tight coupling of inheritance.

Do not use inheritance when simply having a data member will do. Usually this means that the derived type needs to override a base virtual function or needs access to a protected member.

Example
??? Good old Shape example?
Example, bad

Do not represent non-hierarchical domain concepts as class hierarchies.

template<typename T>
class Container {
public:
    // list operations:
    virtual T& get() = 0;
    virtual void put(T&) = 0;
    virtual void insert(Position) = 0;
    // ...
    // vector operations:
    virtual T& operator[](int) = 0;
    virtual void sort() = 0;
    // ...
    // tree operations:
    virtual void balance() = 0;
    // ...
};

Here most overriding classes cannot implement most of the functions required in the interface well. Thus the base class becomes an implementation burden. Furthermore, the user of Container cannot rely on the member functions actually performing a meaningful operations reasonably efficiently; it may throw an exception instead. Thus users have to resort to run-time checking and/or not using this (over)general interface in favor of a particular interface found by a run-time type inquiry (e.g., a dynamic_cast).

Enforcement
  • Look for classes with lots of members that do nothing but throw.
  • Flag every use of a nonpublic base class B where the derived class D does not override a virtual function or access a protected member in B, and B is not one of the following: empty, a template parameter or parameter pack of D, a class template specialized with D.

C.121: If a base class is used as an interface, make it a pure abstract class

Reason

A class is more stable (less brittle) if it does not contain data. Interfaces should normally be composed entirely of public pure virtual functions and a default/empty virtual destructor.

Example
class My_interface {
public:
    // ...only pure virtual functions here ...
    virtual ~My_interface() {}   // or =default
};
Example, bad
class Goof {
public:
    // ...only pure virtual functions here ...
    // no virtual destructor
};

class Derived : public Goof {
    string s;
    // ...
};

void use()
{
    unique_ptr<Goof> p {new Derived{"here we go"}};
    f(p.get()); // use Derived through the Goof interface
    g(p.get()); // use Derived through the Goof interface
} // leak

The Derived is deleted through its Goof interface, so its string is leaked. Give Goof a virtual destructor and all is well.

Enforcement
  • Warn on any class that contains data members and also has an overridable (non-final) virtual function.

C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed

Reason

Such as on an ABI (link) boundary.

Example
struct Device {
    virtual void write(span<const char> outbuf) = 0;
    virtual void read(span<char> inbuf) = 0;
};

class D1 : public Device {
    // ... data ...

    void write(span<const char> outbuf) override;
    void read(span<char> inbuf) override;
};

class D2 : public Device {
    // ... different data ...

    void write(span<const char> outbuf) override;
    void read(span<char> inbuf) override;
};

A user can now use D1s and D2s interchangeably through the interface provided by Device. Furthermore, we can update D1 and D2 in a ways that are not binary compatible with older versions as long as all access goes through Device.

Enforcement
???

C.hierclass: Designing classes in a hierarchy:

C.126: An abstract class typically doesn't need a constructor

Reason

An abstract class typically does not have any data for a constructor to initialize.

Example
???
Exception
  • A base class constructor that does work, such as registering an object somewhere, may need a constructor.
  • In extremely rare cases, you might find it reasonable for an abstract class to have a bit of data shared by all derived classes (e.g., use statistics data, debug information, etc.); such classes tend to have constructors. But be warned: Such classes also tend to be prone to requiring virtual inheritance.
Enforcement

Flag abstract classes with constructors.

C.127: A class with a virtual function should have a virtual or protected destructor

Reason

A class with a virtual function is usually (and in general) used via a pointer to base. Usually, the last user has to call delete on a pointer to base, often via a smart pointer to base, so the destructor should be public and virtual. Less commonly, if deletion through a pointer to base is not intended to be supported, the destructor should be protected and nonvirtual; see C.35.

Example, bad
struct B {
    virtual int f() = 0;
    // ... no user-written destructor, defaults to public nonvirtual ...
};

// bad: class with a resource derived from a class without a virtual destructor
struct D : B {
    string s {"default"};
};

void use()
{
    auto p = make_unique<D>();
    // ...
} // calls B::~B only, leaks the string
Note

There are people who don't follow this rule because they plan to use a class only through a shared_ptr: std::shared_ptr<B> p = std::make_shared<D>(args); Here, the shared pointer will take care of deletion, so no leak will occur from an inappropriate delete of the base. People who do this consistently can get a false positive, but the rule is important -- what if one was allocated using make_unique? It's not safe unless the author of B ensures that it can never be misused, such as by making all constructors private and providing a factory function to enforce the allocation with make_shared.

Enforcement
  • A class with any virtual functions should have a destructor that is either public and virtual or else protected and nonvirtual.
  • Flag delete of a class with a virtual function but no virtual destructor.

C.128: Virtual functions should specify exactly one of virtual, override, or final

Reason

Readability. Detection of mistakes. Writing explicit virtual, override, or final is self-documenting and enables the compiler to catch mismatch of types and/or names between base and derived classes. However, writing more than one of these three is both redundant and a potential source of errors.

Use virtual only when declaring a new virtual function. Use override only when declaring an overrider. Use final only when declaring a final overrider. If a base class destructor is declared virtual, derived class destructors should neither be declared virtual nor override.

Example, bad
struct B {
    void f1(int);
    virtual void f2(int) const;
    virtual void f3(int);
    // ...
};

struct D : B {
    void f1(int);        // bad (hope for a warning): D::f1() hides B::f1()
    void f2(int) const;  // bad (but conventional and valid): no explicit override
    void f3(double);     // bad (hope for a warning): D::f3() hides B::f3()
    // ...
};

struct Better : B {
    void f1(int) override;        // error (caught): D::f1() hides B::f1()
    void f2(int) const override;
    void f3(double) override;     // error (caught): D::f3() hides B::f3()
    // ...
};
Enforcement
  • Compare names in base and derived classes and flag uses of the same name that does not override.
  • Flag overrides with neither override nor final.
  • Flag function declarations that use more than one of virtual, override, and final.

C.129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance

Reason

Implementation details in an interface makes the interface brittle; that is, makes its users vulnerable to having to recompile after changes in the implementation. Data in a base class increases the complexity of implementing the base and can lead to replication of code.

Note

Definition:

  • interface inheritance is the use of inheritance to separate users from implementations, in particular to allow derived classes to be added and changed without affecting the users of base classes.
  • implementation inheritance is the use of inheritance to simplify implementation of new facilities by making useful operations available for implementers of related new operations (sometimes called "programming by difference").

A pure interface class is simply a set of pure virtual functions; see I.25.

In early OOP (e.g., in the 1980s and 1990s), implementation inheritance and interface inheritance were often mixed and bad habits die hard. Even now, mixtures are not uncommon in old code bases and in old-style teaching material.

The importance of keeping the two kinds of inheritance increases

  • with the size of a hierarchy (e.g., dozens of derived classes),
  • with the length of time the hierarchy is used (e.g., decades), and
  • with the number of distinct organizations in which a hierarchy is used (e.g., it can be difficult to distribute an update to a base class)
Example, bad
class Shape {   // BAD, mixed interface and implementation
public:
    Shape();
    Shape(Point ce = {0, 0}, Color co = none): cent{ce}, col {co} { /* ... */}

    Point center() const { return cent; }
    Color color() const { return col; }

    virtual void rotate(int) = 0;
    virtual void move(Point p) { cent = p; redraw(); }

    virtual void redraw();

    // ...
public:
    Point cent;
    Color col;
};

class Circle : public Shape {
public:
    Circle(Point c, int r) :Shape{c}, rad{r} { /* ... */ }

    // ...
private:
    int rad;
};

class Triangle : public Shape {
public:
    Triangle(Point p1, Point p2, Point p3); // calculate center
    // ...
};

Problems:

  • As the hierarchy grows and more data is added to Shape, the constructors gets harder to write and maintain.
  • Why calculate the center for the Triangle? we may never us it.
  • Add a data member to Shape (e.g., drawing style or canvas) and all derived classes and all users needs to be reviewed, possibly changes, and probably recompiled.

The implementation of Shape::move() is an example of implementation inheritance: we have defined move() once and for all for all derived classes. The more code there is in such base class member function implementations and the more data is shared by placing it in the base, the more benefits we gain - and the less stable the hierarchy is.

Example

This Shape hierarchy can be rewritten using interface inheritance:

class Shape {  // pure interface
public:
    virtual Point center() const = 0;
    virtual Color color() const = 0;

    virtual void rotate(int) = 0;
    virtual void move(Point p) = 0;

    virtual void redraw() = 0;

    // ...
};

Note that a pure interface rarely have constructors: there is nothing to construct.

class Circle : public Shape {
public:
    Circle(Point c, int r, Color c) :cent{c}, rad{r}, col{c} { /* ... */ }

    Point center() const override { return cent; }
    Color color() const override { return col; }

    // ...
private:
    Point cent;
    int rad;
    Color col;
};

The interface is now less brittle, but there is more work in implementing the member functions. For example, center has to be implemented by every class derived from Shape.

Example, dual hierarchy

How can we gain the benefit of the stable hierarchies from implementation hierarchies and the benefit of implementation reuse from implementation inheritance. One popular technique is dual hierarchies. There are many ways of implementing the idea of dual hierarchies; here, we use a multiple-inheritance variant.

First we devise a hierarchy of interface classes:

class Shape {   // pure interface
public:
    virtual Point center() const = 0;
    virtual Color color() const = 0;

    virtual void rotate(int) = 0;
    virtual void move(Point p) = 0;

    virtual void redraw() = 0;

    // ...
};

class Circle : public Shape {   // pure interface
public:
    int radius() = 0;
    // ...
};

To make this interface useful, we must provide its implementation classes (here, named equivalently, but in the Impl namespace):

class Impl::Shape : public Shape { // implementation
public:
    // constructors, destructor
    // ...
    virtual Point center() const { /* ... */ }
    virtual Color color() const { /* ... */ }

    virtual void rotate(int) { /* ... */ }
    virtual void move(Point p) { /* ... */ }

    virtual void redraw() { /* ... */ }

    // ...
};

Now Shape is a poor example of a class with an implementation, but bear with us because this is just a simple example of a technique aimed at more complex hierarchies.

class Impl::Circle : public Circle, public Impl::Shape {   // implementation
public:
    // constructors, destructor

    int radius() { /* ... */ }
    // ...
};

And we could extend the hierarchies by adding a Smiley class (:-)):

class Smiley : public Circle { // pure interface
public:
    // ...
};

class Impl::Smiley : Public Smiley, public Impl::Circle {   // implementation
public:
    // constructors, destructor
    // ...
}

There are now two hierarchies:

  • interface: Smiley -> Circle -> Shape
  • implementation: Impl::Smiley -> Impl::Circle -> Impl::Shape

Since each implementation derived from its interface as well as its implementation base class we get a lattice (DAG):

Smiley     ->         Circle     ->  Shape
  ^                     ^               ^
  |                     |               |
Impl::Smiley -> Impl::Circle -> Impl::Shape

As mentioned, this is just one way to construct a dual hierarchy.

Another (related) technique for separating interface and implementation is PIMPL.

Note

There is often a choice between offering common functionality as (implemented) base class functions and free-standing functions (in an implementation namespace). Base classes gives a shorter notation and easier access to shared data (in the base) at the cost of the functionality being available only to users of the hierarchy.

Enforcement
  • Flag a derived to base conversion to a base with both data and virtual functions (except for calls from a derived class member to a base class member)
  • ???

C.130: Redefine or prohibit copying for a base class; prefer a virtual clone function instead

Reason

Copying a base is usually slicing. If you really need copy semantics, copy deeply: Provide a virtual clone function that will copy the actual most-derived type and return an owning pointer to the new object, and then in derived classes return the derived type (use a covariant return type).

Example
class Base {
public:
    virtual owner<Base*> clone() = 0;
    virtual ~Base() = 0;

    Base(const Base&) = delete;
    Base& operator=(const Base&) = delete;
};

class Derived : public Base {
public:
    owner<Derived*> clone() override;
    virtual ~Derived() override;
};

Note that because of language rules, the covariant return type cannot be a smart pointer. See also C.67.

Enforcement
  • Flag a class with a virtual function and a non-user-defined copy operation.
  • Flag an assignment of base class objects (objects of a class from which another has been derived).

C.131: Avoid trivial getters and setters

Reason

A trivial getter or setter adds no semantic value; the data item could just as well be public.

Example
class Point {
    int x;
    int y;
public:
    Point(int xx, int yy) : x{xx}, y{yy} { }
    int get_x() { return x; }
    void set_x(int xx) { x = xx; }
    int get_y() { return y; }
    void set_y(int yy) { y = yy; }
    // no behavioral member functions
};

Consider making such a class a struct -- that is, a behaviorless bunch of variables, all public data and no member functions.

struct Point {
    int x = 0;
    int y = 0;
};
Note

A getter or a setter that converts from an internal type to an interface type is not trivial (it provides a form of information hiding).

Enforcement

Flag multiple get and set member functions that simply access a member without additional semantics.

C.132: Don't make a function virtual without reason

Reason

Redundant virtual increases run-time and object-code size. A virtual function can be overridden and is thus open to mistakes in a derived class. A virtual function ensures code replication in a templated hierarchy.

Example, bad
template<class T>
class Vector {
public:
    // ...
    virtual int size() const { return sz; }   // bad: what good could a derived class do?
private:
    T* elem;   // the elements
    int sz;    // number of elements
};

This kind of "vector" isn't meant to be used as a base class at all.

Enforcement
  • Flag a class with virtual functions but no derived classes.
  • Flag a class where all member functions are virtual and have implementations.

C.133: Avoid protected data

Reason

protected data is a source of complexity and errors. protected data complicated the statement of invariants. protected data inherently violates the guidance against putting data in base classes, which usually leads to having to deal virtual inheritance as well.

Example
???
Note

Protected member function can be just fine.

Enforcement

Flag classes with protected data.

C.134: Ensure all non-const data members have the same access level

Reason

Prevention of logical confusion leading to errors. If the non-const data members don't have the same access level, the type is confused about what it's trying to do. Is it a type that maintains an invariant or simply a collection of values?

Discussion

The core question is: What code is responsible for maintaining a meaningful/correct value for that variable?

There are exactly two kinds of data members:

  • A: Ones that don't participate in the object's invariant. Any combination of values for these members is valid.
  • B: Ones that do participate in the object's invariant. Not every combination of values is meaningful (else there'd be no invariant). Therefore all code that has write access to these variables must know about the invariant, know the semantics, and know (and actively implement and enforce) the rules for keeping the values correct.

Data members in category A should just be public (or, more rarely, protected if you only want derived classes to see them). They don't need encapsulation. All code in the system might as well see and manipulate them.

Data members in category B should be private or const. This is because encapsulation is important. To make them non-private and non-const would mean that the object can't control its own state: An unbounded amount of code beyond the class would need to know about the invariant and participate in maintaining it accurately -- if these data members were public, that would be all calling code that uses the object; if they were protected, it would be all the code in current and future derived classes. This leads to brittle and tightly coupled code that quickly becomes a nightmare to maintain. Any code that inadvertently sets the data members to an invalid or unexpected combination of values would corrupt the object and all subsequent uses of the object.

Most classes are either all A or all B:

  • All public: If you're writing an aggregate bundle-of-variables without an invariant across those variables, then all the variables should be public. By convention, declare such classes struct rather than class
  • All private: If you're writing a type that maintains an invariant, then all the non-const variables should be private -- it should be encapsulated.
Exception

Occasionally classes will mix A and B, usually for debug reasons. An encapsulated object may contain something like non-const debug instrumentation that isn't part of the invariant and so falls into category A -- it isn't really part of the object's value or meaningful observable state either. In that case, the A parts should be treated as A's (made public, or in rarer cases protected if they should be visible only to derived classes) and the B parts should still be treated like B's (private or const).

Enforcement

Flag any class that has non-const data members with different access levels.

C.135: Use multiple inheritance to represent multiple distinct interfaces

Reason

Not all classes will necessarily support all interfaces, and not all callers will necessarily want to deal with all operations. Especially to break apart monolithic interfaces into "aspects" of behavior supported by a given derived class.

Example
???
Note

This is a very common use of inheritance because the need for multiple different interfaces to an implementation is common and such interfaces are often not easily or naturally organized into a single-rooted hierarchy.

Note

Such interfaces are typically abstract classes.

Enforcement

???

C.136: Use multiple inheritance to represent the union of implementation attributes

Reason

??? Herb: Here's the second mention of implementation inheritance. I'm very skeptical, even of single implementation inheritance, never mind multiple implementation inheritance which just seems frightening -- I don't think that even policy-based design really needs to inherit from the policy types. Am I missing some good examples, or could we consider discouraging this as an anti-pattern?

Example
???
Note

This a relatively rare use because implementation can often be organized into a single-rooted hierarchy.

Enforcement

??? Herb: How about opposite enforcement: Flag any type that inherits from more than one non-empty base class?

C.137: Use virtual bases to avoid overly general base classes

Reason

???

Example
???
Note

???

Enforcement

???

C.138: Create an overload set for a derived class and its bases with using

Reason

???

Example
???

C.139: Use final sparingly

Reason

Capping a hierarchy with final is rarely needed for logical reasons and can be damaging to the extensibility of a hierarchy. Capping an individual virtual function with final is error-prone as that final can easily be overlooked when defining/overriding a set of functions.

Example, bad
class Widget { /* ... */ };

// nobody will ever want to improve My_widget (or so you thought)
class My_widget final : public Widget { /* ... */ };

class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that
Example, bad
struct Interface {
    virtual int f() = 0;
    virtual int g() = 0;
};

class My_implementation : public Interface {
    int f() override;
    int g() final;  // I want g() to be FAST!
    // ...
};

class Better_implementation : public My_implementation {
    int f();
    int g();
    // ...
};

void use(Interface* p)
{
    int x = p->f();    // Better_implementation::f()
    int y = p->g();    // My_implementation::g() Surprise?
}

// ...

use(new Better_implementation{});

The problem is easy to see in a small example, but in a large hierarchy with many virtual functions, tools are required for reliably spotting such problems. Consistent use of override would catch this.

Note

Claims of performance improvements from final should be substantiated. Too often, such claims are based on conjecture or experience with other languages.

There are examples where final can be important for both logical and performance reasons. One example is a performance-critical AST hierarchy in a compiler or language analysis tool. New derived classes are not added every year and only by library implementers. However, misuses are (or at least have been) far more common.

Enforcement

Flag uses of final.

C.140: Do not provide different default arguments for a virtual function and an overrider

Reason

That can cause confusion: An overrider does not inherit default arguments.

Example, bad
class Base {
public:
    virtual int multiply(int value, int factor = 2) = 0;
};

class Derived : public Base {
public:
    int multiply(int value, int factor = 10) override;
};

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
Enforcement

Flag default arguments on virtual functions if they differ between base and derived declarations.

C.hier-access: Accessing objects in a hierarchy

C.145: Access polymorphic objects through pointers and references

Reason

If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.

Example
struct B { int a; virtual int f(); };
struct D : B { int b; int f() override; };

void use(B b)
{
    D d;
    B b2 = d;   // slice
    B b3 = b;
}

void use2()
{
    D d;
    use(d);   // slice
}

Both ds are sliced.

Exception

You can safely access a named polymorphic object in the scope of its definition, just don't slice it.

void use3()
{
    D d;
    d.f();   // OK
}
Enforcement

Flag all slicing.

C.146: Use dynamic_cast where class hierarchy navigation is unavoidable

Reason

dynamic_cast is checked at run time.

Example
struct B {   // an interface
    virtual void f();
    virtual void g();
};

struct D : B {   // a wider interface
    void f() override;
    virtual void h();
};

void user(B* pb)
{
    if (D* pd = dynamic_cast<D*>(pb)) {
        // ... use D's interface ...
    }
    else {
        // ... make do with B's interface ...
    }
}
Note

Like other casts, dynamic_cast is overused. Prefer virtual functions to casting. Prefer static polymorphism to hierarchy navigation where it is possible (no run-time resolution necessary) and reasonably convenient.

Note

Some people use dynamic_cast where a typeid would have been more appropriate; dynamic_cast is a general "is kind of" operation for discovering the best interface to an object, whereas typeid is a "give me the exact type of this object" operation to discover the actual type of an object. The latter is an inherently simpler operation that ought to be faster. The latter (typeid) is easily hand-crafted if necessary (e.g., if working on a system where RTTI is -- for some reason -- prohibited), the former (dynamic_cast) is far harder to implement correctly in general.

Consider:

struct B {
    const char * name {"B"};
    virtual const char* id() const { return name; }
    // ...
};

struct D : B {
    const char * name {"D"};
    const char* id() const override { return name; }
    // ...
};

void use()
{
    B* pb1 = new B;
    B* pb2 = new D;

    cout << pb1->id(); // "B"
    cout << pb2->id(); // "D"

    if (pb1->id() == pb2->id()) // *pb1 is the same type as *pb2
    if (pb2->id() == "D") {         // looks innocent
        D* pd = static_cast<D*>(pb1);
        // ...
    }
    // ...
}

The result of pb2->id() == "D" is actually implementation defined. We added it to warn of the dangers of home-brew RTTI. This code may work as expected for years, just to fail on a new machine, new compiler, or a new linker that does not unify character literals.

If you implement your own RTTI, be careful.

Exception

If your implementation provided a really slow dynamic_cast, you may have to use a workaround. However, all workarounds that cannot be statically resolved involve explicit casting (typically static_cast) and are error-prone. You will basically be crafting your own special-purpose dynamic_cast. So, first make sure that your dynamic_cast really is as slow as you think it is (there are a fair number of unsupported rumors about) and that your use of dynamic_cast is really performance critical.

We are of the opinion that current implementations of dynamic_cast are unnecessarily slow. For example, under suitable conditions, it is possible to perform a dynamic_cast in fast constant time. However, compatibility makes changes difficult even if all agree that an effort to optimize is worthwhile.

In very rare cases, if you have measured that the dynamic_cast overhead is material, you have other means to statically guarantee that a downcast will succeed (e.g., you are using CRTP carefully), and there is no virtual inheritance involved, consider tactically resorting static_cast with a prominent comment and disclaimer summarizing this paragraph and that human attention is needed under maintenance because the type system can't verify correctness. Even so, in our experience such "I know what I'm doing" situations are still a known bug source.

Enforcement

Flag all uses of static_cast for downcasts, including C-style casts that perform a static_cast.

C.147: Use dynamic_cast to a reference type when failure to find the required class is considered an error

Reason

Casting to a reference expresses that you intend to end up with a valid object, so the cast must succeed. dynamic_cast will then throw if it does not succeed.

Example
???
Enforcement

???

C.148: Use dynamic_cast to a pointer type when failure to find the required class is considered a valid alternative

Reason

???

Example
???
Enforcement

???

C.149: Use unique_ptr or shared_ptr to avoid forgetting to delete objects created using new

Reason

Avoid resource leaks.

Example
void use(int i)
{
    auto p = new int {7};           // bad: initialize local pointers with new
    auto q = make_unique<int>(9);   // ok: guarantee the release of the memory allocated for 9
    if (0 < i) return;              // maybe return and leak
    delete p;                       // too late
}
Enforcement
  • Flag initialization of a naked pointer with the result of a new
  • Flag delete of local variable

C.150: Use make_unique() to construct objects owned by unique_ptrs

Reason

make_unique gives a more concise statement of the construction. It also ensures exception safety in complex expressions.

Example
unique_ptr<Foo> p {new<Foo>{7}};   // OK: but repetitive

auto q = make_unique<Foo>(7);      // Better: no repetition of Foo

// Not exception-safe: the compiler may interleave the computations of arguments as follows:
//
// 1. allocate memory for Foo,
// 2. construct Foo,
// 3. call bar,
// 4. construct unique_ptr<Foo>.
//
// If bar throws, Foo will not be destroyed, and the memory allocated for it will leak.
f(unique_ptr<Foo>(new Foo()), bar());

// Exception-safe: calls to functions are never interleaved.
f(make_unique<Foo>(), bar());
Enforcement
  • Flag the repetitive usage of template specialization list <Foo>
  • Flag variables declared to be unique_ptr<Foo>

C.151: Use make_shared() to construct objects owned by shared_ptrs

Reason

make_shared gives a more concise statement of the construction. It also gives an opportunity to eliminate a separate allocation for the reference counts, by placing the shared_ptr's use counts next to its object.

Example
// OK: but repetitive; and separate allocations for the Foo and shared_ptr's use count
shared_ptr<Foo> p {new<Foo>{7}};

auto q = make_shared<Foo>(7);   // Better: no repetition of Foo; one object
Enforcement
  • Flag the repetitive usage of template specialization list<Foo>
  • Flag variables declared to be shared_ptr<Foo>

C.152: Never assign a pointer to an array of derived class objects to a pointer to its base

Reason

Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.

Example
struct B { int x; };
struct D : B { int y; };

void use(B*);

D a[] = {{1, 2}, {3, 4}, {5, 6}};
B* p = a;     // bad: a decays to &a[0] which is converted to a B*
p[1].x = 7;   // overwrite D[0].y

use(a);       // bad: a decays to &a[0] which is converted to a B*
Enforcement
  • Flag all combinations of array decay and base to derived conversions.
  • Pass an array as a span rather than as a pointer, and don't let the array name suffer a derived-to-base conversion before getting into the span

C.over: Overloading and overloaded operators

You can overload ordinary functions, template functions, and operators. You cannot overload function objects.

Overload rule summary:

C.160: Define operators primarily to mimic conventional usage

Reason

Minimize surprises.

Example
class X {
public:
    // ...
    X& operator=(const X&); // member function defining assignment
    friend bool operator==(const X&, const X&); // == needs access to representation
                                                // after a = b we have a == b
    // ...
};

Here, the conventional semantics is maintained: Copies compare equal.

Example, bad
X operator+(X a, X b) { return a.v - b.v; }   // bad: makes + subtract
Note

Non-member operators should be either friends or defined in the same namespace as their operands. Binary operators should treat their operands equivalently.

Enforcement

Possibly impossible.

C.161: Use nonmember functions for symmetric operators

Reason

If you use member functions, you need two. Unless you use a non-member function for (say) ==, a == b and b == a will be subtly different.

Example
bool operator==(Point a, Point b) { return a.x == b.x && a.y == b.y; }
Enforcement

Flag member operator functions.

C.162: Overload operations that are roughly equivalent

Reason

Having different names for logically equivalent operations on different argument types is confusing, leads to encoding type information in function names, and inhibits generic programming.

Example

Consider:

void print(int a);
void print(int a, int base);
void print(const string&);

These three functions all print their arguments (appropriately). Conversely:

void print_int(int a);
void print_based(int a, int base);
void print_string(const string&);

These three functions all print their arguments (appropriately). Adding to the name just introduced verbosity and inhibits generic code.

Enforcement

???

C.163: Overload only for operations that are roughly equivalent

Reason

Having the same name for logically different functions is confusing and leads to errors when using generic programming.

Example

Consider:

void open_gate(Gate& g);   // remove obstacle from garage exit lane
void fopen(const char* name, const char* mode);   // open file

The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:

void open(Gate& g);   // remove obstacle from garage exit lane
void open(const char* name, const char* mode ="r");   // open file

The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion. Fortunately, the type system will catch many such mistakes.

Note

Be particularly careful about common and popular names, such as open, move, +, and ==.

Enforcement

???

C.164: Avoid conversion operators

Reason

Implicit conversions can be essential (e.g., double to int) but often cause surprises (e.g., String to C-style string).

Note

Prefer explicitly named conversions until a serious need is demonstrated. By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion) and frequently needed. Do not introduce implicit conversions (through conversion operators or non-explicit constructors) just to gain a minor convenience.

Example, bad
class String {   // handle ownership and access to a sequence of characters
    // ...
    String(czstring p); // copy from *p to *(this->elem)
    // ...
    operator zstring() { return elem; }
    // ...
};

void user(zstring p)
{
    if (*p == "") {
        String s {"Trouble ahead!"};
        // ...
        p = s;
    }
    // use p
}

The string allocated for s and assigned to p is destroyed before it can be used.

Enforcement

Flag all conversion operators.

C.165: Use using for customization points

Reason

To find function objects and functions defined in a separate namespace to "customize" a common function.

Example

Consider swap. It is a general (standard library) function with a definition that will work for just about any type. However, it is desirable to define specific swap()s for specific types. For example, the general swap() will copy the elements of two vectors being swapped, whereas a good specific implementation will not copy elements at all.

namespace N {
    My_type X { /* ... */ };
    void swap(X&, X&);   // optimized swap for N::X
    // ...
}

void f1(N::X& a, N::X& b)
{
    std::swap(a, b);   // probably not what we wanted: calls std::swap()
}

The std::swap() in f1() does exactly what we asked it to do: it calls the swap() in namespace std. Unfortunately, that's probably not what we wanted. How do we get N::X considered?

void f2(N::X& a, N::X& b)
{
    swap(a, b);   // calls N::swap
}

But that may not be what we wanted for generic code. There, we typically want the specific function if it exists and the general function if not. This is done by including the general function in the lookup for the function:

void f3(N::X& a, N::X& b)
{
    using std::swap;  // make std::swap available
    swap(a, b);        // calls N::swap if it exists, otherwise std::swap
}
Enforcement

Unlikely, except for known customization points, such as swap. The problem is that the unqualified and qualified lookups both have uses.

C.166: Overload unary & only as part of a system of smart pointers and references

Reason

The & operator is fundamental in C++. Many parts of the C++ semantics assumes its default meaning.

Example
class Ptr { // a somewhat smart pointer
    Ptr(X* pp) :p(pp) { /* check */ }
    X* operator->() { /* check */ return p; }
    X operator[](int i);
    X operator*();
private:
    T* p;
};

class X {
    Ptr operator&() { return Ptr{this}; }
    // ...
};
Note

If you "mess with" operator & be sure that its definition has matching meanings for ->, [], *, and . on the result type. Note that operator . currently cannot be overloaded so a perfect system is impossible. We hope to remedy that: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf. Note that std::addressof() always yields a built-in pointer.

Enforcement

Tricky. Warn if & is user-defined without also defining -> for the result type.

C.168: Define overloaded operators in the namespace of their operands

Reason

Readability. Ability for find operators using ADL. Avoiding inconsistent definition in different namespaces

Example
struct S { };
bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
S s;

bool x = (s == s);

This is what a default == would do, if we had such defaults.

Example
namespace N {
    struct S { };
    bool operator==(S, S);   // OK: in the same namespace as S, and even next to S
}

N::S s;

bool x = (s == s);  // finds N::operator==() by ADL
Example, bad
struct S { };
S s;

namespace N {
    S::operator!(S a) { return true; }
    S not_s = !s;
}

namespace M {
    S::operator!(S a) { return false; }
    S not_s = !s;
}

Here, the meaning of !s differs in N and M. This can be most confusing. Remove the definition of namespace M and the confusion is replaced by an opportunity to make the mistake.

Note

If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule. For example:

Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);

This may be something best avoided.

See also

This is a special case of the rule that helper functions should be defined in the same namespace as their class.

Enforcement
  • Flag operator definitions that are not it the namespace of their operands

C.167: Use an operator for an operation with its conventional meaning

Reason

Readability. Convention. Reusability. Support for generic code

Example
void cout_my_class(const My_class& c) // confusing, not conventional,not generic
{
    std::cout << /* class members here */;
}

std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
{
    return os << /* class members here */;
}

By itself, cout_my_class would be OK, but it is not usable/composable with code that rely on the << convention for output:

My_class var { /* ... */ };
// ...
cout << "var = " << var << '\n';
Note

There are strong and vigorous conventions for the meaning most operators, such as

  • comparisons (==, !=, <, <=, >, and >=),
  • arithmetic operations (+, -, *, /, and %)
  • access operations (., ->, unary *, and [])
  • assignment (=)

Don't define those unconventionally and don't invent your own names for them.

Enforcement

Tricky. Requires semantic insight.

C.170: If you feel like overloading a lambda, use a generic lambda

Reason

You cannot overload by defining two different lambdas with the same name.

Example
void f(int);
void f(double);
auto f = [](char);   // error: cannot overload variable and function

auto g = [](int) { /* ... */ };
auto g = [](double) { /* ... */ };   // error: cannot overload variables

auto h = [](auto) { /* ... */ };   // OK
Enforcement

The compiler catches the attempt to overload a lambda.

C.union: Unions

A union is a struct where all members start at the same address so that it can hold only one member at a time. A union does not keep track of which member is stored so the programmer has to get it right; this is inherently error-prone, but there are ways to compensate.

A type that is a union plus an indicator of which member is currently held is called a tagged union, a discriminated union, or a variant.

Union rule summary:

C.180: Use unions to save memory

Reason

A union allows a single piece of memory to be used for different types of objects at different times. Consequently, it can be used to save memory when we have several objects that are never used at the same time.

Example
union Value {
    int x;
    double d;
};

Value v = { 123 };  // now v holds an int
cout << v.x << '\n';    // write 123
v.d = 987.654;  // now v holds a double
cout << v.d << '\n';    // write 987.654

But heed the warning: Avoid "naked" unions

Example
// Short string optimization

constexpr size_t buffer_size = 16; // Slightly larger than the size of a pointer

class Immutable_string {
public:
    Immutable_string(const char* str) :
        size(strlen(str))
    {
        if (size < buffer_size)
            strcpy_s(string_buffer, buffer_size, str);
        else {
            string_ptr = new char[size + 1];
            strcpy_s(string_ptr, size + 1, str);
        }
    }

    ~Immutable_string()
    {
        if (size >= buffer_size)
            delete string_ptr;
    }

    const char* get_str() const
    {
        return (size < buffer_size) ? string_buffer : string_ptr;
    }

private:
    // If the string is short enough, we store the string itself
    // instead of a pointer to the string.
    union {
        char* string_ptr;
        char string_buffer[buffer_size];
    };

    const size_t size;
};
Enforcement

???

C.181: Avoid "naked" unions

Reason

A naked union is a union without an associated indicator which member (if any) it holds, so that the programmer has to keep track. Naked unions are a source of type errors.

Example, bad
union Value {
    int x;
    double d;
};

Value v;
v.d = 987.654;  // v holds a double

So far, so good, but we can easily misuse the union:

cout << v.x << '\n';    // BAD, undefined behavior: v holds a double, but we read it as an int

Note that the type error happened without any explicit cast. When we tested that program the last value printed was 1683627180 which it the integer value for the bit pattern for 987.654. What we have here is an "invisible" type error that happens to give a result that could easily look innocent.

And, talking about "invisible", this code produced no output:

v.x = 123;
cout << v.d << '\n';    // BAD: undefined behavior
Alternative

Wrap a union in a class together with a type field.

The soon-to-be-standard variant type (to be found in <variant>) does that for you:

variant<int, double> v;
v = 123;        // v holds an int
int x = get<int>(v);
v = 123.456;    // v holds a double
w = get<double>(v);
Enforcement

???

C.182: Use anonymous unions to implement tagged unions

Reason

A well-designed tagged union is type safe. An anonymous union simplifies the definition of a class with a (tag, union) pair.

Example

This example is mostly borrowed from TC++PL4 pp216-218. You can look there for an explanation.

The code is somewhat elaborate. Handling a type with user-defined assignment and destructor is tricky. Saving programmers from having to write such code is one reason for including variant in the standard.

class Value { // two alternative representations represented as a union
private:
    enum class Tag { number, text };
    Tag type; // discriminant

    union { // representation (note: anonymous union)
        int i;
        string s; // string has default constructor, copy operations, and destructor
    };
public:
    struct Bad_entry { }; // used for exceptions

    ~Value();
    Value& operator=(const Value&);   // necessary because of the string variant
    Value(const Value&);
    // ...
    int number() const;
    string text() const;

    void set_number(int n);
    void set_text(const string&);
    // ...
};

int Value::number() const
{
    if (type != Tag::number) throw Bad_entry{};
    return i;
}

string Value::text() const
{
    if (type != Tag::text) throw Bad_entry{};
    return s;
}

void Value::set_number(int n)
{
    if (type == Tag::text) {
        s.~string();      // explicitly destroy string
        type = Tag::number;
    }
    i = n;
}

void Value::set_text(const string& ss)
{
    if (type == Tag::text)
        s = ss;
    else {
        new(&s) string{ss};   // placement new: explicitly construct string
        type = Tag::text;
    }
}

Value& Value::operator=(const Value& e)   // necessary because of the string variant
{
    if (type == Tag::text && e.type == Tag::text) {
        s = e.s;    // usual string assignment
        return *this;
    }

    if (type == Tag::text) s.~string(); // explicit destroy

    switch (e.type) {
    case Tag::number:
        i = e.i;
        break;
    case Tag::text:
        new(&s)(e.s);   // placement new: explicit construct
        type = e.type;
    }

    return *this;
}

Value::~Value()
{
    if (type == Tag::text) s.~string(); // explicit destroy
}
Enforcement

???

C.183: Don't use a union for type punning

Reason

It is undefined behavior to read a union member with a different type from the one with which it was written. Such punning is invisible, or at least harder to spot than using a named cast. Type punning using a union is a source of errors.

Example, bad
union Pun {
    int x;
    unsigned char c[sizeof(int)];
};

The idea of Pun is to be able to look at the character representation of an int.

void bad(Pun& u)
{
    u.x = 'x';
    cout << u.c[0] << '\n';     // undefined behavior
}

If you wanted to see the bytes of an int, use a (named) cast:

void if_you_must_pun(int& x)
{
    auto p = reinterpret_cast<unsigned char*>(&x);
    cout << p[0] << '\n';     // undefined behavior
    // ...
}

Accessing the result of an reinterpret_cast to a different type from the objects declared type is still undefined behavior, but at least we can see that something tricky is going on.

Note

Unfortunately, unions are commonly used for type punning. We don't consider "sometimes, it works as expected" a strong argument.

Enforcement

???

Enum: Enumerations

Enumerations are used to define sets of integer values and for defining types for such sets of values. There are two kind of enumerations, "plain" enums and class enums.

Enumeration rule summary:

Enum.1: Prefer enumerations over macros

Reason

Macros do not obey scope and type rules. Also, macro names are removed during preprocessing and so usually don't appear in tools like debuggers.

Example

First some bad old code:

// webcolors.h (third party header)
#define RED   0xFF0000
#define GREEN 0x00FF00
#define BLUE  0x0000FF

// productinfo.h
// The following define product subtypes based on color
#define RED    0
#define PURPLE 1
#define BLUE   2

int webby = BLUE;   // webby == 2; probably not what was desired

Instead use an enum:

enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum class Product_info { red = 0, purple = 1, blue = 2 };

int webby = blue;   // error: be specific
Web_color webby = Web_color::blue;

We used an enum class to avoid name clashes.

Enforcement

Flag macros that define integer values.

Enum.2: Use enumerations to represent sets of related named constants

Reason

An enumeration shows the enumerators to be related and can be a named type.

Example
enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
Note

Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:

enum class Product_info { red = 0, purple = 1, blue = 2 };

void print(Product_info inf)
{
    switch (inf) {
    case Product_info::red: cout << "red"; break;
    case Product_info::purple: cout << "purple"; break;
    }
}

Such off-by-one switch`statements are often the results of an added enumerator and insufficient testing.

Enforcement
  • Flag switch-statements where the cases cover most but not all enumerators of an enumeration.
  • Flag switch-statements where the cases cover a few enumerators of an enumeration, but has no default.

Enum.3: Prefer class enums over "plain" enums

Reason

To minimize surprises: traditional enums convert to int too readily.

Example
void Print_color(int color);

enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum Product_info { Red = 0, Purple = 1, Blue = 2 };

Web_color webby = Web_color::blue;

// Clearly at least one of these calls is buggy.
Print_color(webby);
Print_color(Product_info::Blue);

Instead use an enum class:

void Print_color(int color);

enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum class Product_info { red = 0, purple = 1, blue = 2 };

Web_color webby = Web_color::blue;
Print_color(webby);  // Error: cannot convert Web_color to int.
Print_color(Product_info::Red);  // Error: cannot convert Product_info to int.
Enforcement

(Simple) Warn on any non-class enum definition.

Enum.4: Define operations on enumerations for safe and simple use

Reason

Convenience of use and avoidance of errors.

Example
enum class Day { mon, tue, wed, thu, fri, sat, sun };

Day operator++(Day& d)
{
    return d == Day::sun ? Day::mon : Day{++d};
}

Day today = Day::sat;
Day tomorrow = ++today;
Enforcement

Flag repeated expressions cast back into an enumeration.

Enum.5: Don't use ALL_CAPS for enumerators

Reason

Avoid clashes with macros.

Example, bad
 // webcolors.h (third party header)
#define RED   0xFF0000
#define GREEN 0x00FF00
#define BLUE  0x0000FF

// productinfo.h
// The following define product subtypes based on color

enum class Product_info { RED, PURPLE, BLUE };   // syntax error
Enforcement

Flag ALL_CAPS enumerators.

Enum.6: Avoid unnamed enumerations

Reason

If you can't name an enumeration, the values are not related

Example, bad
enum { red = 0xFF0000, scale = 4, is_signed = 1 };

Such code is not uncommon in code written before there were convenient alternative ways of specifying integer constants.

Alternative

Use constexpr values instead. For example:

constexpr int red = 0xFF0000;
constexpr short scale = 4;
constexpr bool is_signed = true;
Enforcement

Flag unnamed enumerations.

Enum.7: Specify the underlying type of an enumeration only when necessary

Reason

The default is the easiest to read and write. int is the default integer type. int is compatible with C enums.

Example
enum class Direction : char { n, s, e, w,
                              ne, nw, se, sw };  // underlying type saves space

enum class Web_color : int { red   = 0xFF0000,
                             green = 0x00FF00,
                             blue  = 0x0000FF };  // underlying type is redundant
Note

Specifying the underlying type is necessary in forward declarations of enumerations:

enum Flags : char;

void f(Flags);

// ....

enum flags : char { /* ... */ };
Enforcement

????

Enum.8: Specify enumerator values only when necessary

Reason

It's the simplest. It avoids duplicate enumerator values. The default gives a consecutive set of values that is good for switch-statement implementations.

Example
enum class Col1 { red, yellow, blue };
enum class Col2 { red = 1, yellow = 2, blue = 2 }; // typo
enum class Month { jan = 1, feb, mar, apr, may, jun,
                   jul, august, sep, oct, nov, dec }; // starting with 1 is conventional
enum class Base_flag { dec = 1, oct = dec << 1, hex = dec << 2 }; // set of bits

Specifying values is necessary to match conventional values (e.g., Month) and where consecutive values are undesirable (e.g., to get separate bits as in Base_flag).

Enforcement
  • Flag duplicate enumerator values
  • Flag explicitly specified all-consecutive enumerator values

R: Resource management

This section contains rules related to resources. A resource is anything that must be acquired and (explicitly or implicitly) released, such as memory, file handles, sockets, and locks. The reason it must be released is typically that it can be in short supply, so even delayed release may do harm. The fundamental aim is to ensure that we don't leak any resources and that we don't hold a resource longer than we need to. An entity that is responsible for releasing a resource is called an owner.

There are a few cases where leaks can be acceptable or even optimal: If you are writing a program that simply produces an output based on an input and the amount of memory needed is proportional to the size of the input, the optimal strategy (for performance and ease of programming) is sometimes simply never to delete anything. If you have enough memory to handle your largest input, leak away, but be sure to give a good error message if you are wrong. Here, we ignore such cases.

R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)

Reason

To avoid leaks and the complexity of manual resource management. C++'s language-enforced constructor/destructor symmetry mirrors the symmetry inherent in resource acquire/release function pairs such as fopen/fclose, lock/unlock, and new/delete. Whenever you deal with a resource that needs paired acquire/release function calls, encapsulate that resource in an object that enforces pairing for you -- acquire the resource in its constructor, and release it in its destructor.

Example, bad

Consider:

void send(X* x, cstring_span destination)
{
    auto port = open_port(destination);
    my_mutex.lock();
    // ...
    send(port, x);
    // ...
    my_mutex.unlock();
    close_port(port);
    delete x;
}

In this code, you have to remember to unlock, close_port, and delete on all paths, and do each exactly once. Further, if any of the code marked ... throws an exception, then x is leaked and my_mutex remains locked.

Example

Consider:

void send(unique_ptr<X> x, cstring_span destination)  // x owns the X
{
    Port port{destination};            // port owns the PortHandle
    lock_guard<mutex> guard{my_mutex}; // guard owns the lock
    // ...
    send(port, x);
    // ...
} // automatically unlocks my_mutex and deletes the pointer in x

Now all resource cleanup is automatic, performed once on all paths whether or not there is an exception. As a bonus, the function now advertises that it takes over ownership of the pointer.

What is Port? A handy wrapper that encapsulates the resource:

class Port {
    PortHandle port;
public:
    Port(cstring_span destination) : port{open_port(destination)} { }
    ~Port() { close_port(port); }
    operator PortHandle() { return port; }

    // port handles can't usually be cloned, so disable copying and assignment if necessary
    Port(const Port&) = delete;
    Port& operator=(const Port&) = delete;
};
Note

Where a resource is "ill-behaved" in that it isn't represented as a class with a destructor, wrap it in a class or use finally

See also: RAII.

R.2: In interfaces, use raw pointers to denote individual objects (only)

Reason

Arrays are best represented by a container type (e.g., vector (owning)) or a span (non-owning). Such containers and views hold sufficient information to do range checking.

Example, bad
void f(int* p, int n)   // n is the number of elements in p[]
{
    // ...
    p[2] = 7;   // bad: subscript raw pointer
    // ...
}

The compiler does not read comments, and without reading other code you do not know whether p really points to n elements. Use a span instead.

Example
void g(int* p, int fmt)   // print *p using format #fmt
{
    // ... uses *p and p[0] only ...
}
Exception

C-style strings are passed as single pointers to a zero-terminated sequence of characters. Use zstring rather than char* to indicate that you rely on that convention.

Note

Many current uses of pointers to a single element could be references. However, where nullptr is a possible value, a reference may not be an reasonable alternative.

Enforcement
  • Flag pointer arithmetic (including ++) on a pointer that is not part of a container, view, or iterator. This rule would generate a huge number of false positives if applied to an older code base.
  • Flag array names passed as simple pointers

R.3: A raw pointer (a T*) is non-owning

Reason

There is nothing (in the C++ standard or in most code) to say otherwise and most raw pointers are non-owning. We want owning pointers identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.

Example
void f()
{
    int* p1 = new int{7};           // bad: raw owning pointer
    auto p2 = make_unique<int>(7);  // OK: the int is owned by a unique pointer
    // ...
}

The unique_ptr protects against leaks by guaranteeing the deletion of its object (even in the presence of exceptions). The T* does not.

Example
template<typename T>
class X {
    // ...
public:
    T* p;   // bad: it is unclear whether p is owning or not
    T* q;   // bad: it is unclear whether q is owning or not
};

We can fix that problem by making ownership explicit:

template<typename T>
class X2 {
    // ...
public:
    owner<T*> p;  // OK: p is owning
    T* q;         // OK: q is not owning
};
Exception

A major class of exception is legacy code, especially code that must remain compilable as C or interface with C and C-style C++ through ABIs. The fact that there are billions of lines of code that violate this rule against owning T*s cannot be ignored. We'd love to see program transformation tools turning 20-year-old "legacy" code into shiny modern code, we encourage the development, deployment and use of such tools, we hope the guidelines will help the development of such tools, and we even contributed (and contribute) to the research and development in this area. However, it will take time: "legacy code" is generated faster than we can renovate old code, and so it will be for a few years.

This code cannot all be rewritten (ever assuming good code transformation software), especially not soon. This problem cannot be solved (at scale) by transforming all owning pointers to unique_ptrs and shared_ptrs, partly because we need/use owning "raw pointers" as well as simple pointers in the implementation of our fundamental resource handles. For example, common vector implementations have one owning pointer and two non-owning pointers. Many ABIs (and essentially all interfaces to C code) use T*s, some of them owning. Some interfaces cannot be simply annotated with owner because they need to remain compilable as C (although this would be a rare good use for a macro, that expands to owner in C++ mode only).

Note

owner<T*> has no default semantics beyond T*. It can be used without changing any code using it and without affecting ABIs. It is simply a indicator to programmers and analysis tools. For example, if an owner<T*> is a member of a class, that class better have a destructor that deletes it.

Example, bad

Returning a (raw) pointer imposes a life-time management uncertainty on the caller; that is, who deletes the pointed-to object?

Gadget* make_gadget(int n)
{
    auto p = new Gadget{n};
    // ...
    return p;
}

void caller(int n)
{
    auto p = make_gadget(n);   // remember to delete p
    // ...
    delete p;
}

In addition to suffering from the problem from leak, this adds a spurious allocation and deallocation operation, and is needlessly verbose. If Gadget is cheap to move out of a function (i.e., is small or has an efficient move operation), just return it "by value" (see "out" return values):

Gadget make_gadget(int n)
{
    Gadget g{n};
    // ...
    return g;
}
Note

This rule applies to factory functions.

Note

If pointer semantics are required (e.g., because the return type needs to refer to a base class of a class hierarchy (an interface)), return a "smart pointer."

Enforcement
  • (Simple) Warn on delete of a raw pointer that is not an owner<T>.
  • (Moderate) Warn on failure to either reset or explicitly delete an owner<T> 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.
  • (Simple) Warn if a function returns an object that was allocated within the function but has a move constructor. Suggest considering returning it by value instead.

R.4: A raw reference (a T&) is non-owning

Reason

There is nothing (in the C++ standard or in most code) to say otherwise and most raw references are non-owning. We want owners identified so that we can reliably and efficiently delete the objects pointed to by owning pointers.

Example
void f()
{
    int& r = *new int{7};  // bad: raw owning reference
    // ...
    delete &r;             // bad: violated the rule against deleting raw pointers
}

See also: The raw pointer rule

Enforcement

See the raw pointer rule

R.5: Don't heap-allocate unnecessarily

Reason

A scoped object is a local object, a global object, or a member. This implies that there is no separate allocation and deallocation cost in excess of that already used for the containing scope or object. The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.

Example

The following example is inefficient (because it has unnecessary allocation and deallocation), vulnerable to exception throws and returns in the ... part (leading to leaks), and verbose:

void f(int n)
{
    auto p = new Gadget{n};
    // ...
    delete p;
}

Instead, use a local variable:

void f(int n)
{
    Gadget g{n};
    // ...
}
Enforcement
  • (Moderate) Warn if an object is allocated and then deallocated on all paths within a function. Suggest it should be a local auto stack object instead.
  • (Simple) Warn if a local Unique_ptr or Shared_ptr is not moved, copied, reassigned or reset before its lifetime ends.

R.6: Avoid non-const global variables

Reason

Global variables can be accessed from everywhere so they can introduce surprising dependencies between apparently unrelated objects. They are a notable source of errors.

Warning: The initialization of global objects is not totally ordered. If you use a global object initialize it with a constant. Note that it is possible to get undefined initialization order even for const objects.

Exception

A global object is often better than a singleton.

Exception

An immutable (const) global does not introduce the problems we try to avoid by banning global objects.

Enforcement

(??? NM: Obviously we can warn about non-const statics ... do we want to?)

R.alloc: Allocation and deallocation

R.10: Avoid malloc() and free()

Reason

malloc() and free() do not support construction and destruction, and do not mix well with new and delete.

Example
class Record {
    int id;
    string name;
    // ...
};

void use()
{
    // p1 may be nullptr
    // *p1 is not initialized; in particular,
    // that string isn't a string, but a string-sized bag of bits
    Record* p1 = static_cast<Record*>(malloc(sizeof(Record)));

    auto p2 = new Record;

    // unless an exception is thrown, *p2 is default initialized
    auto p3 = new(nothrow) Record;
    // p3 may be nullptr; if not, *p3 is default initialized

    // ...

    delete p1;    // error: cannot delete object allocated by malloc()
    free(p2);    // error: cannot free() object allocated by new
}

In some implementations that delete and that free() might work, or maybe they will cause run-time errors.

Exception

There are applications and sections of code where exceptions are not acceptable. Some of the best such examples are in life-critical hard real-time code. Beware that many bans on exception use are based on superstition (bad) or by concerns for older code bases with unsystematic resource management (unfortunately, but sometimes necessary). In such cases, consider the nothrow versions of new.

Enforcement

Flag explicit use of malloc and free.

R.11: Avoid calling new and delete explicitly

Reason

The pointer returned by new should belong to a resource handle (that can call delete). If the pointer returned by new is assigned to a plain/naked pointer, the object can be leaked.

Note

In a large program, a naked delete (that is a delete in application code, rather than part of code devoted to resource management) is a likely bug: if you have N deletes, how can you be certain that you don't need N+1 or N-1? The bug may be latent: it may emerge only during maintenance. If you have a naked new, you probably need a naked delete somewhere, so you probably have a bug.

Enforcement

(Simple) Warn on any explicit use of new and delete. Suggest using make_unique instead.

R.12: Immediately give the result of an explicit resource allocation to a manager object

Reason

If you don't, an exception or a return may lead to a leak.

Example, bad
void f(const string& name)
{
    FILE* f = fopen(name, "r");          // open the file
    vector<char> buf(1024);
    auto _ = finally([f] { fclose(f); })  // remember to close the file
    // ...
}

The allocation of buf may fail and leak the file handle.

Example
void f(const string& name)
{
    ifstream f{name};   // open the file
    vector<char> buf(1024);
    // ...
}

The use of the file handle (in ifstream) is simple, efficient, and safe.

Enforcement
  • Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)

R.13: Perform at most one explicit resource allocation in a single expression statement

Reason

If you perform two explicit resource allocations in one statement, you could leak resources because the order of evaluation of many subexpressions, including function arguments, is unspecified.

Example
void fun(shared_ptr<Widget> sp1, shared_ptr<Widget> sp2);

This fun can be called like this:

// BAD: potential leak
fun(shared_ptr<Widget>(new Widget(a, b)), shared_ptr<Widget>(new Widget(c, d)));

This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments. In particular, the compiler can interleave execution of the two expressions: Memory allocation (by calling operator new) could be done first for both objects, followed by attempts to call the two Widget constructors. If one of the constructor calls throws an exception, then the other object's memory will never be released!

This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement. For example:

shared_ptr<Widget> sp1(new Widget(a, b)); // Better, but messy
fun(sp1, new Widget(c, d));

The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:

fun(make_shared<Widget>(a, b), make_shared<Widget>(c, d)); // Best

Write your own factory wrapper if there is not one already.

Enforcement
  • Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)

R.14: ??? array vs. pointer parameter

Reason

An array decays to a pointer, thereby losing its size, opening the opportunity for range errors.

Example
??? what do we recommend: f(int*[]) or f(int**) ???

Alternative: Use span to preserve size information.

Enforcement

Flag [] parameters.

R.15: Always overload matched allocation/deallocation pairs

Reason

Otherwise you get mismatched operations and chaos.

Example
class X {
    // ...
    void* operator new(size_t s);
    void operator delete(void*);
    // ...
};
Note

If you want memory that cannot be deallocated, =delete the deallocation operation. Don't leave it undeclared.

Enforcement

Flag incomplete pairs.

R.smart: Smart pointers

R.20: Use unique_ptr or shared_ptr to represent ownership

Reason

They can prevent resource leaks.

Example

Consider:

void f()
{
    X x;
    X* p1 { new X };              // see also ???
    unique_ptr<T> p2 { new X };   // unique ownership; see also ???
    shared_ptr<T> p3 { new X };   // shared ownership; see also ???
}

This will leak the object used to initialize p1 (only).

Enforcement

(Simple) Warn if the return value of new or a function call with return value of pointer type is assigned to a raw pointer.

R.21: Prefer unique_ptr over shared_ptr unless you need to share ownership

Reason

A unique_ptr is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).

Example, bad

This needlessly adds and maintains a reference count.

void f()
{
    shared_ptr<Base> base = make_shared<Derived>();
    // use base locally, without copying it -- refcount never exceeds 1
} // destroy base
Example

This is more efficient:

void f()
{
    unique_ptr<Base> base = make_unique<Derived>();
    // use base locally
} // destroy base
Enforcement

(Simple) Warn if a function uses a Shared_ptr with an object allocated within the function, but never returns the Shared_ptr or passes it to a function requiring a Shared_ptr&. Suggest using unique_ptr instead.

R.22: Use make_shared() to make shared_ptrs

Reason

If you first make an object and then give it to a shared_ptr constructor, you (most likely) do one more allocation (and later deallocation) than if you use make_shared() because the reference counts must be allocated separately from the object.

Example

Consider:

shared_ptr<X> p1 { new X{2} }; // bad
auto p = make_shared<X>(2);    // good

The make_shared() version mentions X only once, so it is usually shorter (as well as faster) than the version with the explicit new.

Enforcement

(Simple) Warn if a shared_ptr is constructed from the result of new rather than make_shared.

R.23: Use make_unique() to make unique_ptrs

Reason

For convenience and consistency with shared_ptr.

Note

make_unique() is C++14, but widely available (as well as simple to write).

Enforcement

(Simple) Warn if a unique_ptr is constructed from the result of new rather than make_unique.

R.24: Use std::weak_ptr to break cycles of shared_ptrs

Reason

shared_ptr's rely on use counting and the use count for a cyclic structure never goes to zero, so we need a mechanism to be able to destroy a cyclic structure.

Example
???
Note

??? (HS: A lot of people say "to break cycles", while I think "temporary shared ownership" is more to the point.) ???(BS: breaking cycles is what you must do; temporarily sharing ownership is how you do it. You could "temporarily share ownership" simply by using another shared_ptr.)

Enforcement

??? probably impossible. If we could statically detect cycles, we wouldn't need weak_ptr

R.30: Take smart pointers as parameters only to explicitly express lifetime semantics

Reason

Accepting a smart pointer to a widget is wrong if the function just needs the widget itself. It should be able to accept any widget object, not just ones whose lifetimes are managed by a particular kind of smart pointer. A function that does not manipulate lifetime should take raw pointers or references instead.

Example, bad
// callee
void f(shared_ptr<widget>& w)
{
    // ...
    use(*w); // only use of w -- the lifetime is not used at all
    // ...
};

// caller
shared_ptr<widget> my_widget = /* ... */;
f(my_widget);

widget stack_widget;
f(stack_widget); // error
Example, good
// callee
void f(widget& w)
{
    // ...
    use(w);
    // ...
};

// caller
shared_ptr<widget> my_widget = /* ... */;
f(*my_widget);

widget stack_widget;
f(stack_widget); // ok -- now this works
Enforcement
  • (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.

R.31: If you have non-std smart pointers, follow the basic pattern from std

Reason

The rules in the following section also work for other kinds of third-party and custom smart pointers and are very useful for diagnosing common smart pointer errors that cause performance and correctness problems. You want the rules to work on all the smart pointers you use.

Any type (including primary template or specialization) that overloads unary * and -> is considered a smart pointer:

  • If it is copyable, it is recognized as a reference-counted shared_ptr.
  • If it is not copyable, it is recognized as a unique unique_ptr.
Example
// use Boost's intrusive_ptr
#include<boost/intrusive_ptr.hpp>
void f(boost::intrusive_ptr<widget> p)  // error under rule 'sharedptrparam'
{
    p->foo();
}

// use Microsoft's CComPtr
#include<atlbase.h>
void f(CComPtr<widget> p)               // error under rule 'sharedptrparam'
{
    p->foo();
}

Both cases are an error under the sharedptrparam guideline: p is a Shared_ptr, but nothing about its sharedness is used here and passing it by value is a silent pessimization; these functions should accept a smart pointer only if they need to participate in the widget's lifetime management. Otherwise they should accept a widget*, if it can be nullptr. Otherwise, and ideally, the function should accept a widget&. These smart pointers match the Shared_ptr concept, so these guideline enforcement rules work on them out of the box and expose this common pessimization.

R.32: Take a unique_ptr<widget> parameter to express that a function assumes ownership of a widget

Reason

Using unique_ptr in this way both documents and enforces the function call's ownership transfer.

Example
void sink(unique_ptr<widget>); // consumes the widget

void sink(widget*);            // just uses the widget
Example, bad
void thinko(const unique_ptr<widget>&); // usually not what you want
Enforcement
  • (Simple) Warn if a function takes a Unique_ptr<T> parameter by lvalue reference and does not either assign to it or call reset() on it on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Unique_ptr<T> parameter by reference to const. Suggest taking a const T* or const T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Unique_ptr<T> parameter by rvalue reference. Suggest using pass by value instead.

R.33: Take a unique_ptr<widget>& parameter to express that a function reseats thewidget

Reason

Using unique_ptr in this way both documents and enforces the function call's reseating semantics.

Note

"reseat" means "making a reference or a smart pointer refer to a different object."

Example
void reseat(unique_ptr<widget>&); // "will" or "might" reseat pointer
Example, bad
void thinko(const unique_ptr<widget>&); // usually not what you want
Enforcement
  • (Simple) Warn if a function takes a Unique_ptr<T> parameter by lvalue reference and does not either assign to it or call reset() on it on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Unique_ptr<T> parameter by reference to const. Suggest taking a const T* or const T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Unique_ptr<T> parameter by rvalue reference. Suggest using pass by value instead.

R.34: Take a shared_ptr<widget> parameter to express that a function is part owner

Reason

This makes the function's ownership sharing explicit.

Example, good
void share(shared_ptr<widget>);            // share -- "will" retain refcount

void reseat(shared_ptr<widget>&);          // "might" reseat ptr

void may_share(const shared_ptr<widget>&); // "might" retain refcount
Enforcement
  • (Simple) Warn if a function takes a Shared_ptr<T> parameter by lvalue reference and does not either assign to it or call reset() on it on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Shared_ptr<T> by value or by reference to const and does not copy or move it to another Shared_ptr on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Shared_ptr<T> by rvalue reference. Suggesting taking it by value instead.

R.35: Take a shared_ptr<widget>& parameter to express that a function might reseat the shared pointer

Reason

This makes the function's reseating explicit.

Note

"reseat" means "making a reference or a smart pointer refer to a different object."

Example, good
void share(shared_ptr<widget>);            // share -- "will" retain refcount

void reseat(shared_ptr<widget>&);          // "might" reseat ptr

void may_share(const shared_ptr<widget>&); // "might" retain refcount
Enforcement
  • (Simple) Warn if a function takes a Shared_ptr<T> parameter by lvalue reference and does not either assign to it or call reset() on it on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Shared_ptr<T> by value or by reference to const and does not copy or move it to another Shared_ptr on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Shared_ptr<T> by rvalue reference. Suggesting taking it by value instead.

R.36: Take a const shared_ptr<widget>& parameter to express that it might retain a reference count to the object ???

Reason

This makes the function's ??? explicit.

Example, good
void share(shared_ptr<widget>);            // share -- "will" retain refcount

void reseat(shared_ptr<widget>&);          // "might" reseat ptr

void may_share(const shared_ptr<widget>&); // "might" retain refcount
Enforcement
  • (Simple) Warn if a function takes a Shared_ptr<T> parameter by lvalue reference and does not either assign to it or call reset() on it on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Shared_ptr<T> by value or by reference to const and does not copy or move it to another Shared_ptr on at least one code path. Suggest taking a T* or T& instead.
  • (Simple) ((Foundation)) Warn if a function takes a Shared_ptr<T> by rvalue reference. Suggesting taking it by value instead.

R.37: Do not pass a pointer or reference obtained from an aliased smart pointer

Reason

Violating this rule is the number one cause of losing reference counts and finding yourself with a dangling pointer. Functions should prefer to pass raw pointers and references down call chains. At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive. You need to be sure that the smart pointer cannot inadvertently be reset or reassigned from within the call tree below.

Note

To do this, sometimes you need to take a local copy of a smart pointer, which firmly keeps the object alive for the duration of the function and the call tree.

Example

Consider this code:

// global (static or heap), or aliased local ...
shared_ptr<widget> g_p = ...;

void f(widget& w)
{
    g();
    use(w);  // A
}

void g()
{
    g_p = ...; // oops, if this was the last shared_ptr to that widget, destroys the widget
}

The following should not pass code review:

void my_code()
{
    // BAD: passing pointer or reference obtained from a nonlocal smart pointer
    //      that could be inadvertently reset somewhere inside f or it callees
    f(*g_p);

    // BAD: same reason, just passing it as a "this" pointer
     g_p->func();
}

The fix is simple -- take a local copy of the pointer to "keep a ref count" for your call tree:

void my_code()
{
    // cheap: 1 increment covers this entire function and all the call trees below us
    auto pin = g_p;

    // GOOD: passing pointer or reference obtained from a local unaliased smart pointer
    f(*pin);

    // GOOD: same reason
    pin->func();
}
Enforcement
  • (Simple) Warn if a pointer or reference obtained from a smart pointer variable (Unique_ptr or Shared_ptr) that is nonlocal, or that is local but potentially aliased, is used in a function call. If the smart pointer is a Shared_ptr then suggest taking a local copy of the smart pointer and obtain a pointer or reference from that instead.

ES: Expressions and Statements

Expressions and statements are the lowest and most direct way of expressing actions and computation. Declarations in local scopes are statements.

For naming, commenting, and indentation rules, see NL: Naming and layout.

General rules:

Declaration rules:

Expression rules:

Statement rules:

Arithmetic rules:

ES.1: Prefer the standard library to other libraries and to "handcrafted code"

Reason

Code using a library can be much easier to write than code working directly with language features, much shorter, tend to be of a higher level of abstraction, and the library code is presumably already tested. The ISO C++ standard library is among the most widely known and best tested libraries. It is available as part of all C++ Implementations.

Example
auto sum = accumulate(begin(a), end(a), 0.0);   // good

a range version of accumulate would be even better:

auto sum = accumulate(v, 0.0); // better

but don't hand-code a well-known algorithm:

int max = v.size();   // bad: verbose, purpose unstated
double sum = 0.0;
for (int i = 0; i < max; ++i)
    sum = sum + v[i];
Exception

Large parts of the standard library rely on dynamic allocation (free store). These parts, notably the containers but not the algorithms, are unsuitable for some hard-real time and embedded applications. In such cases, consider providing/using similar facilities, e.g., a standard-library-style container implemented using a pool allocator.

Enforcement

Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?

ES.2: Prefer suitable abstractions to direct use of language features

Reason

A "suitable abstraction" (e.g., library or class) is closer to the application concepts than the bare language, leads to shorter and clearer code, and is likely to be better tested.

Example
vector<string> read1(istream& is)   // good
{
    vector<string> res;
    for (string s; is >> s;)
        res.push_back(s);
    return res;
}

The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:

char** read2(istream& is, int maxelem, int maxstring, int* nread)   // bad: verbose and incomplete
{
    auto res = new char*[maxelem];
    int elemcount = 0;
    while (is && elemcount < maxelem) {
        auto s = new char[maxstring];
        is.read(s, maxstring);
        res[elemcount++] = s;
    }
    nread = &elemcount;
    return res;
}

Once the checking for overflow and error handling has been added that code gets quite messy, and there is the problem remembering to delete the returned pointer and the C-style strings that array contains.

Enforcement

Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?