April 13, 2023
Editors:
编辑:
This is a living document under continuous improvement.
Had it been an open-source (code) project, this would have been release 0.8.
Copying, use, modification, and creation of derivative works from this project is licensed under an MIT-style license.
Contributing to this project requires agreeing to a Contributor License. See the accompanying LICENSE file for details.
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:
问题:
You can read an explanation of the scope and structure of this Guide or just jump straight in:
你可以阅读本指南范围和结构的解释,也可以直接进入
Supporting sections:
支持部分:
You can sample rules for specific language features:
您可以选取特定语言功能的规则:
class
:concept
:throw
–explicit
–virtual
class
派生类:dynamic_cast
throw
–noexcept
–try
–for
:inline
:{}
–public
, private
, and protected
:protected
static_assert
:struct
:template
:unsigned
:virtual
:virtual
–You can look at design concepts used to express the rules:
您可以查看用于表达规则的设计概念:
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 effective use of the ISO C++ standard (currently C++20, but almost all of our recommendations also apply to C++17, C++14 and C++11).
In other words, what would you like your code to look like in 5 years’ time, given that you can start now? In 10 years’ time?
The guidelines are focused on relatively high-level issues, such as interfaces, resource management, memory management, and concurrency.
Such rules affect application architecture and library design.
Following the rules will lead to code that is statically type safe, has no resource leaks, and catches many more programming logic errors than is common in code today.
And it will run fast – you can afford to do things right.
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 might very well be too strict.
We expect to have to introduce more exceptions to better accommodate real-world needs.
We also need more rules.
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.
This is a set of core guidelines for modern C++ (currently C++20 and C++17) taking likely future enhancements and ISO Technical Specifications (TSs) into account.
The aim is to help C++ programmers to write simpler, more efficient, more maintainable code.
Introduction summary:
All C++ programmers. This includes programmers who might consider C.
The purpose of this document is to help developers to adopt modern C++ (currently C++20 and C++17) and to achieve a more uniform style across code bases.
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:
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.
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 completely convert a large code base all at once.
These guidelines are not meant to be complete or exact in every language-technical detail.
For the final word on language definition issues, including every exception to general rules and every feature, see the ISO C++ standard.
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 precise to the point where a person (or machine) can follow them without thinking.
The enforcement parts try to be that, but we would rather leave a rule or a definition a bit vague
and open to interpretation than specify something precisely and wrong.
Sometimes, precision comes only with time and experience.
Design is not (yet) a form of Math.
The rules are not perfect.
A rule can do harm by prohibiting something that is useful in a given situation.
A rule can do harm by failing to prohibit something that enables a serious error in a given situation.
A rule can do a lot of harm by being vague, ambiguous, unenforceable, or by enabling every solution to a problem.
It is impossible to completely meet the “do no harm” criteria.
Instead, our aim is the less ambitious: “Do the most good for most programmers”;
if you cannot live with a rule, object to it, ignore it, but don’t water it down until it becomes meaningless.
Also, suggest an improvement.
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.
So, we need subsetting to meet a variety of needs.
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 bloat”.
Where appropriate, we label a rule (in the Enforcement sections) with the name of groups of related rules (called “profiles”).
A rule can be part of several profiles, or none.
For a start, we have a few profiles corresponding to common needs (desires, ideals):
T
as a U
through casts, unions, or varargs)delete
or multiple delete
) and no access to invalid objects (dereferencing nullptr
, using a dangling reference).The profiles are intended to be used by tools, but also serve as an aid to the human reader.
We do not limit our comment in the Enforcement sections to things we know how to enforce; some comments are mere wishes that might inspire some tool builder.
Tools that implement these rules shall respect the following syntax to explicitly suppress a rule:
[[gsl::suppress(tag)]]
and optionally with a message (following usual C++11 standard attribute syntax):
[[gsl::suppress(tag, justification: "message")]]
where
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)
"message"
is a string literal
Each rule (guideline, suggestion) can have several parts:
new
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.
Examples are written to illustrate rules.
f
, base
, and x
.vector
rather than std::vector
.This is not a language manual.
It is meant to be helpful, rather than complete, fully accurate on technical details, or a guide to existing code.
Recommended information sources can be found in the references.
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”).
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.
Compilers don’t read comments (or design documents) and neither do many programmers (consistently).
What is expressed in code has defined semantics and can (in principle) be checked by compilers and other tools.
class Date {
public:
Month month() const; // do
int month(); // don't
// ...
};
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.
This loop is a restricted form of std::find
:
void f(vector& v)
{
string val;
cin >> val;
// ...
int index = -1; // bad, plus should use gsl::index
for (int i = 0; i < v.size(); ++i) {
if (v[i] == val) {
index = i;
break;
}
}
// ...
}
A much clearer expression of intent would be:
void f(vector& v)
{
string val;
cin >> val;
// ...
auto p = find(begin(v), end(v), val); // better
// ...
}
A well-designed library expresses intent (what is to be done, rather than just how something is being done) far better than direct use of language features.
A C++ programmer should know the basics of the standard library, and use it where appropriate.
Any programmer should know the basics of the foundation libraries of the project being worked on, and use them appropriately.
Any programmer using these guidelines should know the guidelines support library, and use it appropriately.
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(23_m / 10s); // meters per second
We could have accepted a plain (unit-less) double
as a delta, but that would have been error-prone.
If we wanted both absolute speed and deltas, we would have defined a Delta
type.
Very hard in general.
const
consistently (check if member functions modify their object; check if functions modify arguments passed by pointer or reference)This is a set of guidelines for writing ISO Standard C++.
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 might have slightly different
behaviors and edge case behavior as a direct result of not having a rigorous
standard definition. With sufficient use of any such extension, expected
portability will be impacted.
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)
).
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.
Use an up-to-date C++ compiler (currently C++20 or C++17) with a set of options that do not accept extensions.
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.
gsl::index i = 0;
while (i < v.size()) {
// ... do something with v[i] ...
}
The intent of “just” looping over the elements of v
is not expressed here. The implementation detail of an index is exposed (so that it might be misused), and i
outlives the scope of the loop, which might or might not be intended. The reader cannot know from just this section of code.
Better:
for (const auto& x : v) { /* do something with the value of x */ }
Now, there is no explicit mention of the iteration mechanism, and the loop operates on a reference to const
elements so that accidental modification cannot happen. If modification is desired, say so:
for (auto& x : v) { /* modify x */ }
For more details about for-statements, see ES.71.
Sometimes better still, use a named algorithm. This example uses the for_each
from the Ranges TS because it directly expresses the intent:
for_each(v, [](int x) { /* do something with the value of x */ });
for_each(par, v, [](int x) { /* do something with the value of x */ });
The last variant makes it clear that we are not interested in the order in which the elements of v
are handled.
A programmer should be familiar with
Alternative formulation: Say what should be done, rather than just how it should be done.
Some language constructs express intent better than others.
If two int
s are meant to be the coordinates of a 2D point, say so:
draw_line(int, int, int, int); // obscure: (x1,y1,x2,y2)? (x,y,h,w)? ...?
// need to look up documentation to know
draw_line(Point, Point); // clearer
Look for common patterns for which there are better alternatives
for
loops vs. range-for
loopsf(T*, int)
interfaces vs. f(span)
interfacesnew
and delete
There is a huge scope for cleverness and semi-automated program transformation.
Ideally, a program would be completely statically (compile-time) type safe.
Unfortunately, that is not possible. Problem areas:
These areas are sources of serious problems (e.g., crashes and security violations).
We try to provide alternative techniques.
We can ban, restrain, or detect the individual problem categories separately, as required and feasible for individual programs.
Always suggest an alternative.
For example:
variant
(in C++17)span
(from the GSL)span
narrow
or narrow_cast
(from the GSL) where they are necessaryCode clarity and performance.
You don’t need to write error handlers for errors caught at compile time.
// 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 fails to achieve what it is trying to achieve (because overflow is undefined) and should be replaced with a simple static_assert
:
// Int is an alias used for integers
static_assert(sizeof(Int) >= 4); // do: compile-time check
Or better still just use the type system and replace Int
with int32_t
.
void read(int* p, int n); // read max n integers into *p
int a[100];
read(a, 1000); // bad, off the end
better
void read(span 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.
Leaving hard-to-detect errors in a program is asking for crashes and bad results.
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).
// 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.
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?).
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 n);
void g3(int n)
{
f3(make_unique(n), m); // bad: pass ownership and size separately
}
We need to pass the pointer and the number of elements as an integral object:
extern void f4(vector&); // separately compiled, possibly dynamically loaded
extern void f4(span); // separately compiled, possibly dynamically loaded
// NB: this assumes the calling code is ABI-compatible, using a
// compatible C++ compiler and the same stdlib implementation
void g3(int n)
{
vector v(n);
f4(v); // pass a reference, retain ownership
f4(span{v}); // pass a view, retain ownership
}
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.
How do we transfer both ownership and all information needed for validating use?
vector f5(int n) // OK: move
{
vector v(n);
// ... initialize v ...
return v;
}
unique_ptr f6(int n) // bad: loses n
{
auto p = make_unique(n);
// ... initialize *p ...
return p;
}
owner f7(int n) // bad: loses n and we might forget to delete
{
owner p = new int[n];
// ... initialize *p ...
return p;
}
Avoid “mysterious” crashes.
Avoid errors leading to (possibly unrecognized) wrong results.
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.
If we could check subscripts for out of range access, then the error would not be discovered until p[10]
was accessed.
We could check earlier and improve the code:
void increment2(span 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
// ...
}
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).
Excess checking can be costly.
There are cases where checking early is inefficient because you might never need the value, or might only need part of the value that is more easily checked than the whole. Similarly, don’t add validity checks that change the asymptotic behavior of your interface (e.g., don’t add a O(n)
check to an interface with an average complexity of O(1)
).
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.
???
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.
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
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.
Enforcing the lifetime safety 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.
owner
from the GSL.new
and delete
fopen
, malloc
, and strdup
)This is C++.
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
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) throw Nullptr_error{};
int n = strlen(p);
auto buf = new char[n];
if (!buf) throw Allocation_error{};
for (int i = 0; i < n; ++i) buf[i] = p[i];
// ... manipulate buffer ...
X x;
x.ch = 'a';
x.s = string(n); // give x.s space for *p
for (gsl::index i = 0; i < x.s.size(); ++i) x.s[i] = buf[i]; // copy buf into x.s
delete[] buf;
return x;
}
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.
void lower(zstring s)
{
for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}
This is actually an example from production code.
We can see that in our condition we have i < strlen(s)
. This expression will be evaluated on every iteration of the loop, which means that strlen
must walk through string every loop to discover its length. While the string contents are changing, it’s assumed that tolower
will not affect the length of the string, so it’s better to cache the length outside the loop and not incur that cost each iteration.
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.
Many more specific rules aim at the overall goals of simplicity and elimination of gratuitous waste.
operator++
or operator--
function. Prefer using the prefix form instead. (Note: “User-defined non-defaulted” is intended to reduce noise. Review this enforcement if it’s still too noisy in practice.)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
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.
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 v;
v.reserve(100);
// ...
for (int x; cin >> x; ) {
// ... check that x is valid ...
v.push_back(x);
}
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.
There are many things that are done better “by machine”.
Computers don’t tire or get bored by repetitive tasks.
We typically have better things to do than repeatedly do routine tasks.
Run a static analyzer to verify that your code follows the guidelines you want it to follow.
See
There are many other kinds of tools, such as source code repositories, build tools, etc.,
but those are beyond the scope of these guidelines.
Be careful not to become dependent on over-elaborate or over-specialized tool chains.
Those can make your otherwise portable code non-portable.
Using a well-designed, well-documented, and well-supported library saves time and effort;
its quality and documentation are likely to be greater than what you could do
if the majority of your time must be spent on an implementation.
The cost (time, effort, money, etc.) of a library can be shared over many users.
A widely used library is more likely to be kept up-to-date and ported to new systems than an individual application.
Knowledge of a widely-used library can save time on other/future projects.
So, if a suitable library exists for your application domain, use it.
std::sort(begin(v), end(v), std::greater<>());
Unless you are an expert in sorting algorithms and have plenty of time,
this is more likely to be correct and to run faster than anything you write for a specific application.
You need a reason not to use the standard library (or whatever foundational libraries your application uses) rather than a reason to use it.
By default use
If no well-designed, well-documented, and well-supported library exists for an important domain,
maybe you should design and implement it, and then use it.
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:
const
global variablesExpects()
for expressing preconditionsEnsures()
for expressing postconditionsT*
) or reference (T&
)not_null
See also:
Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.
Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:
int round(double d)
{
return (round_up) ? ceil(d) : d; // don't: "invisible" dependency
}
It will not be obvious to a caller that the meaning of two calls of round(7.2)
might give different results.
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.
Reporting through non-local variables (e.g., errno
) is easily ignored. For example:
// don't: no test of fprintf'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 function templates and sets of functions can be classes or class templates.
const
global variablesNon-const
global variables hide dependencies and make the dependencies subject to unpredictable changes.
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
?
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.
A global object is often better than a singleton.
Global constants are useful.
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 non-local data (or data passed by reference) while another thread executes the callee, we can have a data race.
Every pointer or reference to mutable data is a potential data race.
Using global pointers or references to access and change non-const, and otherwise non-global,
data isn’t a better alternative to non-const global variables since that doesn’t solve the issues of hidden dependencies or potential race conditions.
You cannot have a race condition on immutable data.
References: See the rules for calling functions.
The rule is “avoid”, not “don’t use.” Of course there will be (rare) exceptions, such as cin
, cout
, and cerr
.
(Simple) Report all non-const
variables declared at namespace scope and global pointers/references to non-const data.
Singletons are basically complicated global objects in disguise.
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.
If you don’t want a global object to change, declare it const
or constexpr
.
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 must delete
that object in some suitably thread-safe way.
That’s error-prone, so we don’t use that technique unless
myX
is in multi-threaded code,X
object needs to be destroyed (e.g., because it releases a resource), andX
’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.
Very hard in general.
singleton
.Types are the simplest and best documentation, improve legibility due to their well-defined meaning, and are checked at compile time.
Also, precisely typed code is often optimized better.
Consider:
void pass(void* data); // weak and under qualified type void* is suspicious
Callers are unsure what types are allowed and if the data may
be mutated as const
is not specified. Note all pointer types
implicitly convert to void*
, so it is easy for callers to provide this value.
The callee must static_cast
data to an unverified type to use it.
That is error-prone and verbose.
Only use const void*
for passing in data in designs that are indescribable in C++. Consider using a variant
or a pointer to base instead.
Alternative: Often, a template parameter can eliminate the void*
turning it into a T*
or T&
.
For generic code these T
s can be general or concept constrained template parameters.
Consider:
draw_rect(100, 200, 100, 500); // what do the numbers specify?
draw_rect(p.x, p.y, 10, 20); // what units are 10 and 20 in?
It is clear that the caller is describing a rectangle, but it is unclear what parts they relate to. Also, an int
can carry arbitrary forms of information, including values of many units, so we must guess about the meaning of the four int
s. Most likely, the first two are an x
,y
coordinate pair, but what are the last two?
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)).
Consider:
set_settings(true, false, 42); // what do the numbers specify?
The parameter types and their values do not communicate what settings are being specified or what those values mean.
This design is more explicit, safe and legible:
alarm_settings s{};
s.enabled = true;
s.displayMode = alarm_settings::mode::spinning_light;
s.frequency = alarm_settings::every_10_seconds;
set_settings(s);
For the case of a set of boolean values consider using a flags enum
; a pattern that expresses a set of boolean values.
enable_lamp_options(lamp_option::on | lamp_option::animate_state_transitions);
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);
}
std::chrono::duration
types 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
void blink_led(duration time_to_blink) // good -- accepts any unit
{
// assuming that millisecond is the smallest relevant unit
auto milliseconds_to_blink = duration_cast(time_to_blink);
// ...
// do something with milliseconds_to_blink
// ...
}
void use()
{
blink_led(2s);
blink_led(1500ms);
}
void*
as a parameter or return type.bool
parameter.Arguments have meaning that might constrain their proper use in the callee.
Consider:
double sqrt(double x);
Here x
must be non-negative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
double sqrt(double x); // x must be non-negative
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.
Prefer a formal specification of requirements, such as Expects(p);
.
If that is infeasible, use English text in comments, such as // the sequence [p:q) is ordered using <
.
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.
(Not enforceable)
See also: The rules for passing pointers. ???
Expects()
for expressing preconditionsTo make it clear that the condition is a precondition and to enable tool use.
int area(int height, int width)
{
Expects(height > 0 && width > 0); // good
if (height <= 0 || width <= 0) my_error(); // obscure
// ...
}
Preconditions can be stated in many ways, including comments, if
-statements, and assert()
.
This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and might have the wrong semantics (do you always want to abort in debug mode and check nothing in productions runs?).
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.
Expects()
can also be used to check a condition in the middle of an algorithm.
No, using unsigned
is not a good way to sidestep the problem of ensuring that a value is non-negative.
(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.
To detect misunderstandings about the result and possibly catch erroneous implementations.
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;
}
Consider a famous security bug:
void f() // problematic
{
char buffer[MAX];
// ...
memset(buffer, 0, sizeof(buffer));
}
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, sizeof(buffer));
Ensures(buffer[0] == 0);
}
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.
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.
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 _ {m};
// ...
}
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.
(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.
Ensures()
for expressing postconditionsTo make it clear that the condition is a postcondition and to enable tool use.
void f()
{
char buffer[MAX];
// ...
memset(buffer, 0, MAX);
Ensures(buffer[0] == 0);
}
Postconditions can be stated in many ways, including comments, if
-statements, and assert()
.
This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and might have the wrong semantics.
Alternative: Postconditions of the form “this resource must be released” are best expressed by RAII.
Ideally, that Ensures
should be part of the interface, but that’s not easily done.
For now, we place it in the definition (function body).
Once language support becomes available (e.g., see the contract proposal) we will adopt the standard version of preconditions, postconditions, and assertions.
(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.
Make the interface precisely specified and compile-time checkable in the (not so distant) future.
Use the C++20 style of requirements specification. For example:
template
requires input_iterator && equality_comparable_with, Val>
Iter find(Iter first, Iter last, Val v)
{
// ...
}
See also: Generic programming and concepts.
Warn if any non-variadic template parameter is not constrained by a concept (in its declaration or mentioned in a requires
clause).
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.
int printf(const char* ...); // bad: return negative number if output fails
template
// good: throw system_error if unable to start the new thread
explicit thread(F&& f, Args&&... args);
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 should always check.
However, if failing to make a connection is considered an error, then a failure should throw an 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.
If you can’t use exceptions (e.g., because your code is full of old-style raw-pointer use or because there are hard-real-time constraints), consider using a style that returns a pair of values:
int val;
int error_code;
tie(val, error_code) = do_something();
if (error_code) {
// ... handle the error or exit ...
}
// ... use val ...
This style unfortunately leads to uninitialized variables.
Since C++17 the “structured bindings” feature can be used to initialize variables directly from the return value:
auto [val, error_code] = do_something();
if (error_code) {
// ... handle the error or exit ...
}
// ... use val ...
We don’t consider “performance” a valid reason not to use exceptions.
See also: I.5 and I.7 for reporting precondition and postcondition violations.
errno
.T*
) or reference (T&
)If there is any doubt whether the caller or the callee owns an object, leaks or premature destruction will occur.
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 compute(args) // good
{
vector 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 often less efficient than returning the object itself,
so use smart pointers only if 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 guidelines support library:
owner compute(args) // It is now clear that ownership is transferred
{
owner res = new X{};
// ...
return res;
}
This tells analysis tools that res
is an owner.
That is, its value must be delete
d or transferred to another owner, as is done here by the return
.
owner
is used similarly in the implementation of resource handles.
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, use of smart pointer arguments, and value return.
delete
of a raw pointer that is not an owner
. Suggest use of standard-library resource handle or use of owner
.reset
or explicitly delete
an owner
pointer on every code path.new
or a function call with an owner
return value is assigned to a raw pointer or non-owner
reference.not_null
To help avoid dereferencing nullptr
errors.
To improve performance by avoiding redundant checks for nullptr
.
int length(const char* p); // it is not clear whether length(nullptr) is valid
length(nullptr); // OK?
int length(not_null 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.
not_null
is defined in the guidelines support library.
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 p);
Note: length()
is, of course, std::strlen()
in disguise.
nullptr
before access, on all control-flow paths, then warn it should be declared not_null
.nullptr
on all return paths, then warn the return type should be declared not_null
.(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.
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.
Consider using explicit spans:
void copy(span r, span r2); // copy r to r2
Consider:
void draw(Shape* p, int n); // poor interface; poor code
Circle arr[10];
// ...
draw(arr, 10);
Passing 10
as the n
argument might be a mistake: the most common convention is to assume [0:n)
but that is nowhere stated. Worse is that the call of draw()
compiled at all: there was an implicit conversion from array to pointer (array decay) and then another implicit conversion from Circle
to Shape
. There is no way that draw()
can safely iterate through that array: it has no way of knowing the size of the elements.
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 arr[10];
// ...
draw2(span(arr)); // deduce the number of elements
draw2(arr); // deduce the element type and array size
void draw3(span);
draw3(arr); // error: cannot convert Circle[10] to span
This draw2()
passes the same amount of information to draw()
, but makes the fact that it is supposed to be a range of Circle
s explicit. See ???.
Use zstring
and czstring
to represent C-style, zero-terminated strings.
But when doing so, use std::string_view
or span
from the GSL to prevent range errors.
Complex initialization can lead to undefined order of execution.
// 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 shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global variables.
Order of initialization problems become particularly difficult to handle in concurrent code.
It is usually best to avoid global (namespace scope) objects altogether.
constexpr
functionsextern
objectsHaving many arguments opens opportunities for confusion. Passing lots of arguments is often costly compared to alternatives.
The two most common reasons why functions have too many parameters are:
Missing an abstraction.
There is an abstraction missing, so that a compound value is being
passed as individual elements instead of as a single object that enforces an invariant.
This not only expands the parameter list, but it leads to errors because the component values
are no longer protected by an enforced invariant.
Violating “one function, one responsibility.”
The function is trying to do more than one job and should probably be refactored.
The standard-library merge()
is at the limit of what we can comfortably handle:
template
OutputIterator merge(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
Note that this is because of problem 1 above – missing abstraction. Instead of passing a range (abstraction), STL passed iterator pairs (unencapsulated component values).
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
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
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 a standard library concept to define the notion of three types that must be usable for merging:
template
requires mergeable
Out merge(In1 r1, In2 r2, Out result);
The safety Profiles recommend replacing
void f(int* some_ints, int some_ints_length); // BAD: C style, unsafe
with
void f(gsl::span some_ints); // GOOD: safe, bounds-checked
Here, using an abstraction has safety and robustness benefits, and naturally also reduces the number of parameters.
How many parameters are too many? Try to use fewer than four (4) parameters.
There are functions that are best expressed with four individual parameters, but not many.
Alternative: Use better abstraction: 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.
Adjacent arguments of the same type are easily swapped by mistake.
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)
If the order of the parameters is not important, there is no problem:
int max(int a, int b);
Don’t pass arrays as pointers, pass an object representing a range (e.g., a span
):
void copy_n(span p, span q); // copy from p to q
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 tends to make invocations of this clear to future readers, as the parameters
are often filled in by name at the call site.
Only the interface’s designer can adequately address the source of violations of this guideline.
(Simple) Warn if two consecutive parameters share the same type
We are still looking for a less-simple enforcement.
Abstract classes that are empty (have no non-static member data) are more likely to be stable than base classes with state.
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 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 Shape
s are best represented without an outline defined as a sequence of Point
s. Using an abstract class is better:
class Shape { // better: Shape is a pure interface
public:
virtual Point center() const = 0; // pure virtual functions
virtual void draw() const = 0;
virtual void rotate(int) = 0;
// ...
// ... no data members ...
// ...
virtual ~Shape() = default;
};
(Simple) Warn if a pointer/reference to a class C
is assigned to a pointer/reference to a base of C
and the base class contains data members.
Different compilers implement different binary layouts for classes, exception handling, function names, and other implementation details.
Common ABIs are emerging on some platforms freeing you from the more draconian restrictions.
If you use a single compiler, you can use full C++ in interfaces. That might require recompilation after an upgrade to a new compiler version.
(Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
Because private data members participate in class layout and private member functions participate in overload resolution, changes to those
implementation details require recompilation of all users of a class that uses them. A non-polymorphic interface class holding a pointer to
implementation (Pimpl) can isolate the users of a class from changes in its implementation at the cost of an indirection.
interface (widget.h)
class widget {
class impl;
std::unique_ptr pimpl;
public:
void draw(); // public API that will be forwarded to the implementation
widget(int); // defined in the implementation file
~widget(); // defined in the implementation file, where impl is a complete type
widget(widget&&) noexcept; // defined in the implementation file
widget(const widget&) = delete;
widget& operator=(widget&&) noexcept; // defined in the implementation file
widget& operator=(const widget&) = delete;
};
implementation (widget.cpp)
class widget::impl {
int n; // private data
public:
void draw(const widget& w) { /* ... */ }
impl(int n) : n(n) {}
};
void widget::draw() { pimpl->draw(*this); }
widget::widget(int n) : pimpl{std::make_unique(n)} {}
widget::widget(widget&&) noexcept = default;
widget::~widget() = default;
widget& widget::operator=(widget&&) noexcept = default;
See GOTW #100 and cppreference for the trade-offs and additional implementation details associated with this idiom.
(Not enforceable) It is difficult to reliably identify where an interface forms part of an ABI.
To keep code simple and safe.
Sometimes, ugly, unsafe, or error-prone techniques are necessary for logical or performance reasons.
If so, keep them local, rather than “infecting” interfaces so that larger groups of programmers have to be aware of the
subtleties.
Implementation complexity should, if at all possible, not leak through interfaces into user code.
Consider a program that, depending on some form of input (e.g., arguments to main
), should consume input
from a file, from the command line, or from standard input.
We might write
bool owned;
owner inp;
switch (source) {
case std_in: owned = false; inp = &cin; break;
case command_line: owned = true; inp = new istringstream{argv[2]}; break;
case file: owned = true; inp = new ifstream{argv[2]}; break;
}
istream& in = *inp;
This violated the rule against uninitialized variables,
the rule against ignoring ownership,
and the rule against magic constants.
In particular, someone has to remember to somewhere write
if (owned) delete inp;
We could handle this particular example by using unique_ptr
with a special deleter that does nothing for cin
,
but that’s complicated for novices (who can easily encounter this problem) and the example is an example of a more general
problem where a property that we would like to consider static (here, ownership) needs infrequently be addressed
at run time.
The common, most frequent, and safest examples can be handled statically, so we don’t want to add cost and complexity to those.
But we must also cope with the uncommon, less-safe, and necessarily more expensive cases.
Such examples are discussed in [Str15].
So, we write a class
class Istream { [[gsl::suppress(lifetime)]]
public:
enum Opt { from_line = 1 };
Istream() { }
Istream(zstring p) : owned{true}, inp{new ifstream{p}} {} // read from file
Istream(zstring p, Opt) : owned{true}, inp{new istringstream{p}} {} // read from command line
~Istream() { if (owned) delete inp; }
operator istream&() { return *inp; }
private:
bool owned = false;
istream* inp = &cin;
};
Now, the dynamic nature of istream
ownership has been encapsulated.
Presumably, a bit of checking for potential errors would be added in real code.
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:
constexpr
noexcept
T*
or T&
arguments rather than smart pointersParameter passing expression rules:
const
const
X&&
and std::move
the parameterTP&&
and only std::forward
the parameterT*
over T&
when “no argument” is a valid optionParameter passing semantic rules:
T*
or owner
to designate a single objectnot_null
to indicate that “null” is not a valid valuespan
or a span_p
to designate a half-open sequencezstring
or a not_null
to designate a C-style stringunique_ptr
to transfer ownership where a pointer is neededshared_ptr
to share ownershipValue return semantic rules:
T*
to indicate a position (only)T&
when copy is undesirable and “returning no object” isn’t neededT&&
int
is the return type for main()
T&
from assignment operatorsstd::move(local)
const T
Other function rules:
this
or any class data member, don’t use [=]
default captureva_arg
argumentsFunctions have strong similarities to lambdas and function objects.
See also: C.lambdas: Function objects and lambdas
A function definition is a function declaration that also specifies the function’s implementation, the function body.
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.
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 int
s.
There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use.
For a tiny example, this looks OK, but if the input operation, the output operation, and the error handling had been more complicated the tangled
mess could become hard to understand.
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.
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);
The shortest code is not always the best for performance or maintainability.
Loop bodies, including lambdas used as loop bodies, rarely need to be named.
However, large loop bodies (e.g., dozens of lines or dozens of pages) can be a problem.
The rule Keep functions short and simple implies “Keep loop bodies short.”
Similarly, lambdas used as callback arguments are sometimes non-trivial, yet unlikely to be reusable.
A function that performs a single operation is simpler to understand, test, and reuse.
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 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";
}
tuple
for multiple return values.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
Consider:
double simple_func(double val, int flag1, int flag2)
// simple_func: takes a value and calculates the expected ASIC output,
// given the two mode flags.
{
double intermediate;
if (flag1 > 0) {
intermediate = func1(val);
if (flag2 % 2)
intermediate = sqrt(intermediate);
}
else if (flag1 == -1) {
intermediate = func1(-val);
if (flag2 % 2)
intermediate = sqrt(-intermediate);
flag1 = -flag1;
}
if (abs(flag2) > 10) {
intermediate = func2(intermediate);
}
switch (flag2 / 10) {
case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
break;
case 2: return finalize(intermediate, 13.1);
default: break;
}
return finalize(intermediate, 0.);
}
This is too complex.
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 func1_tau(double val, int flag1, int flag2)
{
// ???
}
double simple_func(double val, int flag1, int flag2)
// simple_func: takes a value and calculates the expected ASIC output,
// given the two mode flags.
{
if (flag1 > 0)
return func1_muon(val, flag2);
if (flag1 == -1)
// handled by func1_tau: flag1 = -flag1;
return func1_tau(-val, flag1, flag2);
return 0.;
}
“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.
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.
constexpr
constexpr
is needed to tell the compiler to allow compile-time evaluation.
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()
.
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
}
Don’t try to make all functions constexpr
.
Most computation is best done at run time.
Any API that might eventually depend on high-level run-time configuration or
business logic should not be made constexpr
. Such customization can not be
evaluated by the compiler, and any constexpr
functions that depended upon
that API would have to be refactored or drop constexpr
.
Impossible and unnecessary.
The compiler gives an error if a non-constexpr
function is called where a constant is required.
inline
Some optimizers are good at inlining without hints from the programmer, but don’t rely on it.
Measure! Over the last 40 years or so, we have been promised compilers that can inline better than humans without hints from humans.
We are still waiting.
Specifying inline (explicitly, or implicitly when writing member functions inside a class definition) encourages the compiler to do a better job.
inline string cat(const string& s, const string& s2) { return s + s2; }
Do not put an inline
function in what is meant to be a stable interface unless you are certain that it will not change.
An inline function is part of the ABI.
constexpr
implies inline
.
Member functions defined in-class are inline
by default.
Function templates (including member functions of class templates A
and member function templates A::function
) are normally defined in headers and therefore inline.
Flag inline
functions that are more than three statements and could have been declared out of line (such as class member functions).
noexcept
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.
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.
constexpr
functions can throw when evaluated at run time, so you might need conditional noexcept
for some of those.
You can use noexcept
even on functions that can throw:
vector collect(istream& is) noexcept
{
vector 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 might be just the right thing to do;
terminate()
might generate suitable error log information (but after memory runs out it is hard to do anything clever).
You must be aware of the execution environment that your code is running when
deciding whether to tag a function noexcept
, especially because of the issue
of throwing and allocation. Code that is intended to be perfectly general (like
the standard library and other utility code of that sort) needs to support
environments where a bad_alloc
exception could be handled meaningfully.
However, most programs and execution environments cannot meaningfully
handle a failure to allocate, and aborting the program is the cleanest and
simplest response to an allocation failure in those cases. If you know that
your application code cannot respond to an allocation failure, it could be
appropriate to add noexcept
even on functions that allocate.
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.
Destructors, swap
functions, move operations, and default constructors should never throw.
See also C.44.
noexcept
, yet cannot throw.swap
, move
, destructors, and default constructors.T*
or T&
arguments rather than smart pointersPassing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended.
A function that does not manipulate lifetime should take raw pointers or references instead.
Passing by smart pointer restricts the use of a function to callers that use smart pointers.
A function that needs a widget
should be able to accept any widget
object, not just ones whose lifetimes are managed by a particular kind of smart pointer.
Passing a shared smart pointer (e.g., std::shared_ptr
) implies a run-time cost.
// accepts any int*
void f(int*);
// can only accept ints for which you want to transfer ownership
void g(unique_ptr);
// can only accept ints for which you are willing to share ownership
void g(shared_ptr);
// doesn't change ownership, but requires a particular ownership of the caller
void h(const unique_ptr&);
// accepts any int
void h(int&);
// callee
void f(shared_ptr& w)
{
// ...
use(*w); // only use of w -- the lifetime is not used at all
// ...
};
// caller
shared_ptr my_widget = /* ... */;
f(my_widget);
widget stack_widget;
f(stack_widget); // error
// callee
void f(widget& w)
{
// ...
use(w);
// ...
};
// caller
shared_ptr my_widget = /* ... */;
f(*my_widget);
widget stack_widget;
f(stack_widget); // ok -- now this works
We can catch many common cases of dangling pointers statically (see lifetime safety profile). Function arguments naturally live for the lifetime of the function call, and so have fewer lifetime problems.
operator->
or operator*
) that is copyable but the function only calls any of: operator*
, operator->
or get()
.T*
or T&
instead.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.T*
or T&
instead.See also:
T*
over T&
when “no argument” is a valid optionPure functions are easier to reason about, sometimes easier to optimize (and even parallelize), and sometimes can be memoized.
template
auto square(T t) { return t * t; }
Not possible.
Readability.
Suppression of unused parameter warnings.
widget* find(const set& s, const widget& w, Hint); // once upon a time, a hint was used
Allowing parameters to be unnamed was introduced in the early 1980s to address this problem.
If parameters are conditionally unused, declare them with the [[maybe_unused]]
attribute.
For example:
template
Value* find(const set& s, const Value& v, [[maybe_unused]] Hint h)
{
if constexpr (sizeof(Value) > CacheSize)
{
// a hint is used only if Value is of a certain size
}
}
Flag named unused parameters.
Documentation, readability, opportunity for reuse.
struct Rec {
string name;
string addr;
int id; // unique identifier
};
bool same(const Rec& a, const Rec& b)
{
return a.id == b.id;
}
vector find_id(const string& name); // find all records for "name"
auto x = find_if(vr.begin(), vr.end(),
[&](Rec& r) {
if (r.name.size() != n.size()) return false; // name to compare to is in n
for (int i = 0; i < r.name.size(); ++i)
if (tolower(r.name[i]) != tolower(n[i])) return false;
return true;
}
);
There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.
bool compare_insensitive(const string& a, const string& b)
{
if (a.size() != b.size()) return false;
for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
return true;
}
auto x = find_if(vr.begin(), vr.end(),
[&](Rec& r) { return compare_insensitive(r.name, n); }
);
Or maybe (if you prefer to avoid the implicit name binding to n):
auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };
auto x = find_if(vr.begin(), vr.end(),
[](const Rec& r) { return cmp_to_n(r.name); }
);
whether functions, lambdas, or operators.
for_each
and similar control flow algorithms.That makes the code concise and gives better locality than alternatives.
auto earlyUsersEnd = std::remove_if(users.begin(), users.end(),
[](const User &a) { return a.id > 100; });
Naming a lambda can be useful for clarity even if it is used only once.
There are a variety of ways to pass parameters to a function and to return values.
Using “unusual and clever” techniques causes surprises, slows understanding by other programmers, and encourages bugs.
If you really feel the need for an optimization beyond the common techniques, measure to ensure that it really is an improvement, and document/comment because the improvement might not be portable.
The following tables summarize the advice in the following Guidelines, F.16-21.
Normal parameter passing:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ggo1OEZq-1689844036546)(./param-passing-normal.png “Normal parameter passing”)]
Advanced parameter passing:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H30xhven-1689844036546)(./param-passing-advanced.png “Advanced parameter passing”)]
Use the advanced techniques only after demonstrating need, and document that need in a comment.
For passing sequences of characters see String.
To express shared ownership using shared_ptr
types, rather than following guidelines F.16-21,
follow R.34, R.35, and R.36.
const
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.
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:
&&
. See F.18.const&
(for lvalues),&&
(for rvalues) and in the body std::move
s it to its destination. Essentially this overloads a “will-move-from”; see F.18.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); // input only, and moves ownership of 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.18 and F.19).
A reference can be assumed to refer to a valid object (language rule).
There is no (legitimate) “null reference.”
If you need the notion of an optional value, use a pointer, std::optional
, or a special value used to denote “no value.”
2 * sizeof(void*)
.const
instead.const
has a size less or equal than 2 * sizeof(void*)
. Suggest passing by value instead.const
is move
d.To express shared ownership using shared_ptr
types, follow R.34 or R.36,
depending on whether or not the function unconditionally takes a reference to the argument.
const
This makes it clear to callers that the object is assumed to be modified.
void update(Record& r); // assume that update writes to r
Some user-defined and standard library types, such as span
or the iterators
are cheap to copy and may be passed by value, while doing so has
mutable (in-out) reference semantics:
void increment_all(span a)
{
for (auto&& e : a)
++e;
}
A T&
argument can pass information into a function as well as out of it.
Thus T&
could be an in-out-parameter. That can in itself be a problem and a source of errors:
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).
A bad logic error can happen if the writer of g()
incorrectly assumes the size of the buffer
.
const
parameters that do not write to them.const
parameter being passed by reference is move
d.X&&
and std::move
the parameterIt’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.
void sink(vector&& v) // sink takes ownership of whatever the argument owned
{
// usually there might be const accesses of v here
store_somewhere(std::move(v));
// usually no more use of v here; it is moved-from
}
Note that the std::move(v)
makes it possible for store_somewhere()
to leave v
in a moved-from state.
That could be dangerous.
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
void sink(std::unique_ptr p)
{
// use p ... possibly std::move(p) onward somewhere else
} // p gets destroyed
If the “will-move-from” parameter is a shared_ptr
follow R.34 and pass the shared_ptr
by value.
X&&
parameters (where X
is not a template type parameter name) where the function body uses them without std::move
.TP&&
and only std::forward
the parameterIf 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.
Usually you forward the entire parameter (or parameter pack, using ...
) exactly once on every static control flow path:
template
inline auto invoke(F f, Args&&... args)
{
return f(forward(args)...);
}
Sometimes you may forward a composite parameter piecewise, each subobject once on every static control flow path:
template
inline auto test(PairLike&& pairlike)
{
// ...
f1(some, args, and, forward(pairlike).first); // forward .first
f2(and, forward(pairlike).second, in, another, call); // forward .second
}
TP&&
parameter (where TP
is a template type parameter name) and does anything with it other than std::forward
ing it exactly once on every static path, or std::forward
ing it more than once but qualified with a different data member exactly once on every static path.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.
// OK: return pointers to elements with the value x
vector find_all(const vector&, int x);
// Bad: place pointers to elements with value x in-out
void find_all(const vector&, vector& out, int x);
A struct
of many (individually cheap-to-move) elements might be in aggregate expensive to move.
unique_ptr
or shared_ptr
.array
), consider allocating it on the free store and return a handle (e.g., unique_ptr
), or passing it in a reference to non-const
target object to fill (to be used as an out-parameter).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.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
The return value optimization doesn’t handle the assignment case, but the move assignment does.
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
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.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
(including pair
), possibly with the extra convenience of tie
or structured bindings (C++17) at the call site.
Prefer using a named struct where there are semantics to the returned value. Otherwise, a nameless tuple
is useful in generic code.
// 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 f(const string& input)
{
// ...
return {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
, 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 are 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);
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& in, string& s); // much like std::operator>>()
for (string s; in >> s; ) {
// do something with line
}
Here, both s
and in
are used as in-out parameters.
We pass in
by (non-const
) reference to be able to manipulate its state.
We pass s
to avoid repeated allocations.
By reusing s
(passed by reference), we allocate new memory only when we need to expand s
’s capacity.
This technique is sometimes called the “caller-allocated out” pattern and is particularly useful for types,
such as string
and vector
, that needs to do free store allocations.
To compare, if we passed out all values as return values, we would something like this:
pair get_string(istream& in) // not recommended
{
string s;
in >> s;
return {in, move(s)};
}
for (auto p = get_string(cin); p.first; ) {
// do something with p.second
}
We consider that significantly less elegant with significantly less performance.
For a truly strict reading of this rule (F.21), the exception isn’t really an exception because it relies on in-out parameters,
rather than the plain out parameters mentioned in the rule.
However, we prefer to be explicit, rather than subtle.
In many cases, it can be useful to return a specific, user-defined type.
For example:
struct Distance {
int value;
int unit = 1; // 1 means meters
};
Distance d1 = measure(obj1); // access d1.value and d1.unit
auto d2 = measure(obj2); // access d2.value and d2.unit
auto [value, unit] = measure(obj3); // access value and unit; somewhat redundant
// to people who know measure()
auto [x, y] = measure(obj4); // don't; it's likely to be confusing
The overly-generic pair
and tuple
should be used only when the value returned represents independent entities rather than an abstraction.
Another example, use a specific type along the lines of variant
, rather than using the generic tuple
.
When the tuple to be returned is initialized from local variables that are expensive to copy,
explicit move
may be helpful to avoid copying:
pair f(const string& input)
{
LargeObject large1 = g(input);
LargeObject large2 = h(input);
// ...
return { move(large1), move(large2) }; // no copies
}
Alternatively,
pair f(const string& input)
{
// ...
return { g(input), h(input) }; // no copies, no moves
}
Note this is different from the return move(...)
anti-pattern from ES.56
const
member function, or passes on as a non-const
.T*
over T&
when “no argument” is a valid optionA 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.
string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string
{
if (!p) return string{}; // p might be nullptr; remember to check
return string{p};
}
void print(const vector& r)
{
// r refers to a vector; no check needed
}
It is possible, but not valid C++ to construct a reference that is essentially a nullptr
(e.g., T* p = nullptr; T& r = *p;
).
That error is very uncommon.
If you prefer the pointer notation (->
and/or *
vs. .
), not_null
provides the same guarantee as T&
.
T*
or owner
to designate a single objectReadability: it makes the meaning of a plain pointer clear.
Enables significant tool support.
In traditional C and C++ code, plain T*
is used for many weakly-related purposes, such as:
nullptr
This makes it hard to understand what the code does and is supposed to do.
It complicates checking and tool support.
void use(int* p, int n, char* s, int* q)
{
p[n - 1] = 666; // Bad: we don't know if p points to n elements;
// assume it does not or use span
cout << s; // Bad: we don't know if that s points to a zero-terminated array of char;
// assume it does not or use zstring
delete q; // Bad: we don't know if *q is allocated on the free store;
// assume it does not or use owner
}
better
void use2(span p, zstring s, owner q)
{
p[p.size() - 1] = 666; // OK, a range error can be caught
cout << s; // OK
delete q; // OK
}
owner
represents ownership, zstring
represents a C-style string.
Also: Assume that a T*
obtained from a smart pointer to T
(e.g., unique_ptr
) points to a single element.
See also: Support library
See also: Do not pass an array as a single pointer
not_null
to indicate that “null” is not a valid valueClarity. A function with a not_null
parameter makes it clear that the caller of the function is responsible for any nullptr
checks that might be necessary.
Similarly, a function with a return value of not_null
makes it clear that the caller of the function does not need to check for nullptr
.
not_null
makes it obvious to a reader (human or machine) that a test for nullptr
is not necessary before dereference.
Additionally, when debugging, owner
and not_null
can be instrumented to check for correctness.
Consider:
int length(Record* p);
When I call length(p)
should I check if p
is nullptr
first? Should the implementation of length()
check if p
is nullptr
?
// it is the caller's job to make sure p != nullptr
int length(not_null p);
// the implementor of length() must assume that p == nullptr is possible
int length(Record* p);
A not_null
is assumed not to be the nullptr
; a T*
might be the nullptr
; both can be represented in memory as a T*
(so no run-time overhead is implied).
not_null
is not just for built-in pointers. It works for unique_ptr
, shared_ptr
, and other pointer-like types.
nullptr
(or equivalent) within a function, suggest it is declared not_null
instead.nullptr
(or equivalent) within the function and sometimes is not.not_null
pointer is tested against nullptr
within a function.span
or a span_p
to designate a half-open sequenceInformal/non-explicit ranges are a source of errors.
X* find(span r, const X& v); // find v in r
vector vec;
// ...
auto p = find({vec.begin(), vec.end()}, X{}); // find X{} in vec
Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure.
In particular, given a pair of arguments (p, n)
designating an array [p:p+n)
,
it is in general impossible to know if there really are n
elements to access following *p
.
span
and span_p
are simple helper classes designating a [p:q)
range and a range starting with p
and ending with the first element for which a predicate is true, respectively.
A span
represents a range of elements, but how do we manipulate elements of that range?
void f(span s)
{
// range traversal (guaranteed correct)
for (int x : s) cout << x << '\n';
// C-style traversal (potentially checked)
for (gsl::index 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]);
}
A span
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
(Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use span
instead.
zstring
or a not_null
to designate a C-style stringC-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.
If you don’t need null termination, use string_view
.
Consider:
int length(const char* p);
When I call length(s)
should I check if s
is nullptr
first? Should the implementation of length()
check if p
is 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 p);
zstring
does not represent ownership.
See also: Support library
unique_ptr
to transfer ownership where a pointer is neededUsing unique_ptr
is the cheapest way to pass a pointer safely.
See also: C.50 regarding when to return a shared_ptr
from a factory.
unique_ptr get_shape(istream& is) // assemble shape from input stream
{
auto kind = read_header(is); // read header and identify the next shape on input
switch (kind) {
case kCircle:
return make_unique(is);
case kTriangle:
return make_unique(is);
// ...
}
}
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).
(Simple) Warn if a function returns a locally allocated raw pointer. Suggest using either unique_ptr
or shared_ptr
instead.
shared_ptr
to share ownershipUsing std::shared_ptr
is the standard way to represent shared ownership. That is, the last owner deletes the object.
shared_ptr im { read_image(somewhere) };
std::thread t0 {shade, args0, top_left, im};
std::thread t1 {shade, args1, top_right, im};
std::thread t2 {shade, args2, bottom_left, im};
std::thread t3 {shade, args3, bottom_right, im};
// detach threads
// last thread to finish deletes the image
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).
Have a single object own the shared object (e.g. a scoped object) and destroy that (preferably implicitly) when all users have completed.
(Not enforceable) This is a too complex pattern to reliably detect.
T*
to indicate a position (only)That’s what pointers are good for.
Returning a T*
to transfer ownership is a misuse.
Node* find(Node* t, const string& s) // find s in a binary tree of Nodes
{
if (!t || 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.
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.
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
delete
, std::free()
, etc. applied to a plain T*
.new
, malloc()
, etc. assigned to a plain T*
.To avoid the crashes and data corruption that can result from the use of such a dangling pointer.
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
.
fx
and gx
were of different types.fx
or gx
was a type with an invariant.Fortunately, most (all?) modern compilers catch and warn against this simple case.
This applies to references as well:
int& f()
{
int x = 7;
// ...
return x; // Bad: returns reference to object that is about to be destroyed
}
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.
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
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.
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.
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.
T&
when copy is undesirable and “returning no object” isn’t neededThe 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.
class Car
{
array w;
// ...
public:
wheel& get_wheel(int i) { Expects(i < w.size()); return w[i]; }
// ...
};
void use()
{
Car c;
wheel& w0 = c.get_wheel(0); // w0 has the same lifetime as c
}
Flag functions where no return
expression could yield nullptr
T&&
It’s asking to return a reference to a destroyed temporary object.
A &&
is a magnet for temporary objects.
A returned rvalue reference goes out of scope at the end of the full expression to which it is returned:
auto&& x = max(0, 1); // OK, so far
foo(x); // Undefined behavior
This kind of use is a frequent source of bugs, often incorrectly reported as a compiler bug.
An implementer of a function should avoid setting such traps for users.
The lifetime safety profile will (when completely implemented) catch such problems.
Returning an rvalue reference is fine when the reference to the temporary is being passed “downward” to a callee;
then, the temporary is guaranteed to outlive the function call (see F.18 and F.19).
However, it’s not fine when passing such a reference “upward” to a larger caller scope.
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&&
).
Assume that F
returns by value:
template
auto&& wrapper(F f)
{
log_call(typeid(f)); // or whatever instrumentation
return f(); // BAD: returns a reference to a temporary
}
Better:
template
auto wrapper(F f)
{
log_call(typeid(f)); // or whatever instrumentation
return f(); // OK
}
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 &&
.
Flag any use of &&
as a return type, except in std::move
and std::forward
.
int
is the return type for main()
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.
void main() { /* ... */ }; // bad, not C++
int main()
{
std::cout << "This is the way to do it\n";
}
We mention this only because of the persistence of this error in the community.
Note that despite its non-void return type, the main function does not require an explicit return statement.
T&
from assignment operatorsThe convention for operator overloads (especially on concrete 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.”
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.
class Foo
{
public:
...
Foo& operator=(const Foo& rhs)
{
// Copy members.
...
return *this;
}
};
This should be enforced by tooling by checking the return type (and return
value) of any assignment operator.
return std::move(local)
With guaranteed copy elision, it is now almost always a pessimization to expressly use std::move
in a return statement.
S f()
{
S result;
return std::move(result);
}
S f()
{
S result;
return result;
}
This should be enforced by tooling by checking the return expression .
const T
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 fct(); // bad: that "const" is more trouble than it is worth
void g(vector& vx)
{
// ...
fct() = vx; // prevented by the "const"
// ...
vx = fct(); // 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 that it prevents (very frequent) use of move semantics.
See also: F.20, the general item about “out” output values
const
value. To fix: Remove const
to return a non-const
value instead.Functions can’t capture local variables or be defined 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.
// writing a function that should only take an int or a string
// -- overloading is natural
void f(int);
void f(const string&);
// writing a function object that needs to capture local state and appear
// at statement or expression scope -- a lambda is natural
vector v = lots_of_work();
for (int tasknum = 0; tasknum < max; ++tasknum) {
pool.run([=, &v] {
/*
...
... process 1 / max - th of v, the tasknum - th chunk
...
*/
});
}
pool.join();
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.
auto x = [](int i) { /*...*/; };
) that captures nothing and appears at global scope. Write an ordinary function instead.Default arguments simply provide 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.
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);
Default arguments for virtual functions
f(int)
, f(int, const string&)
, f(int, const string&, double)
). (Note: Review this enforcement if it’s too noisy in practice.)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.
The efficiency consideration is that most types are cheaper to pass by reference than by value.
The correctness consideration is that many calls want to perform side effects on the original object at the call site (see example below). Passing by value prevents this.
Unfortunately, there is no simple way to capture by reference to const
to get the efficiency for a local call but also prevent side effects.
Here, a large object (a network message) is passed to an iterative algorithm, and it is not efficient or correct to copy the message (which might not be copyable):
std::for_each(begin(sockets), end(sockets), [&message](auto& socket)
{
socket.send(message);
});
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
Flag a lambda that captures by reference, but is used other than locally within the function scope or passed to a function by reference. (Note: This rule is an approximation, but does flag passing by pointer as those are more likely to be stored by the callee, writing to a heap location accessed via a parameter, returning the lambda, etc. The Lifetime rules will also provide general rules that flag escaping pointers and references including via lambdas.)
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.
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); });
int local = 42;
// Want a copy of local.
// Since a copy of local is made, it will
// always be available for the call.
thread_pool.queue_work([=] { process(local); });
If a non-local pointer must be captured, consider using unique_ptr
; this handles both lifetime and synchronization.
If the this
pointer must be captured, consider using [*this]
capture, which creates a copy of the entire object.
const
and non-local contextthis
or any class data member, don’t use [=]
default captureIt’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.
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(0, 42);
x = 43;
lambda(); // calls use(0, 43);
// ...
auto lambda2 = [i, this] { use(i, x); }; // ok, most explicit and least confusing
// ...
}
};
If you intend to capture a copy of all class data members, consider C++17 [*this]
.
[=]
and also captures this
(whether explicitly or via the default capture and a use of this
in the body)va_arg
argumentsReading from a va_arg
assumes that the correct type was actually passed.
Passing to varargs assumes the correct type will be read.
This is fragile because it cannot generally be enforced to be safe in the language and so relies on programmer discipline to get it right.
int sum(...)
{
// ...
while (/*...*/)
result += va_arg(list, int); // BAD, assumes it will be passed ints
// ...
}
sum(3, 2); // ok
sum(3.14159, 2.71828); // BAD, undefined
template
auto sum(Args... args) // GOOD, and much more flexible
{
return (... + args); // note: C++17 "fold expression"
}
sum(3, 2); // ok: 5
sum(3.14159, 2.71828); // ok: ~5.85987
variant
argumentsinitializer_list
(homogeneous)Declaring a ...
parameter is sometimes useful for techniques that don’t involve actual argument passing, notably to declare “take-anything” functions so as to disable “everything else” in an overload set or express a catchall case in a template metaprogram.
va_list
, va_start
, or va_arg
.[[suppress(types)]]
.Shallow nesting of conditions makes the code easier to follow. It also makes the intent clearer.
Strive to place the essential code at outermost scope, unless this obscures intent.
Use a guard-clause to take care of exceptional cases and return early.
// Bad: Deep nesting
void foo() {
...
if (x) {
computeImportantThings(x);
}
}
// Bad: Still a redundant else.
void foo() {
...
if (!x) {
return;
}
else {
computeImportantThings(x);
}
}
// Good: Early return, no redundant else
void foo() {
...
if (!x)
return;
computeImportantThings(x);
}
// Bad: Unnecessary nesting of conditions
void foo() {
...
if (x) {
if (y) {
computeImportantThings(x);
}
}
}
// Good: Merge conditions + return early
void foo() {
...
if (!(x && y))
return;
computeImportantThings(x);
}
Flag a redundant else
.
Flag a functions whose body is simply a conditional statement enclosing a block.
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:
struct
s or class
es)class
if the class has an invariant; use struct
if the data members can vary independentlyclass
rather than struct
if any member is non-publicSubsections:
struct
s or class
es)Ease of comprehension.
If data is related (for fundamental reasons), that fact should be reflected in code.
void draw(int x, int y, int x2, int y2); // BAD: unnecessary implicit relationships
void draw(Point from, Point to); // better
A simple class without virtual functions implies no space or time overhead.
From a language perspective class
and struct
differ only in the default visibility of their members.
Probably impossible. Maybe a heuristic looking for data items used together is possible.
class
if the class has an invariant; use struct
if the data members can vary independentlyReadability.
Ease of comprehension.
The use of class
alerts the programmer to the need for an invariant.
This is a useful convention.
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.
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
};
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.
See also:
class
protected
dataLook for struct
s with all data private and class
es with public members.
An explicit distinction between interface and implementation improves readability and simplifies maintenance.
class Date {
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;
// ...
private:
// ... some representation ...
};
For example, we can now change the representation of a Date
without affecting its users (recompilation is likely, though).
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 function template 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).
???
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.
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
.
This rule becomes even better if C++ gets “uniform function call”.
The language requires virtual
functions to be members, and not all virtual
functions directly access data.
In particular, members of an abstract class rarely do.
Note multi-methods.
The language requires operators =
, ()
, []
, and ->
to be members.
An overload set could have some members that do not directly access private
data:
class Foobar {
public:
void foo(long x) { /* manipulate private data */ }
void foo(double x) { foo(std::lround(x)); }
// ...
private:
// ...
};
Similarly, a set of functions could be designed to be used in a chain:
x.scale(0.5).rotate(45).set_color(Color::red);
Typically, some but not all of such functions directly access private
data.
virtual
member functions that do not touch data members directly.virtual
functions.private
members.this
.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.
namespace Chrono { // here we keep time-related services
class Time { /* ... */ };
class Date { /* ... */ };
// helper functions:
bool operator==(Date, Date);
Date next_weekday(Date);
// ...
}
This is especially important for overloaded operators.
Mixing a type definition and the definition of another entity in the same declaration is confusing and unnecessary.
struct Data { /*...*/ } data{ /*...*/ };
struct Data { /*...*/ };
Data data{ /*...*/ };
}
of a class or enumeration definition is not followed by a ;
. The ;
is missing.class
rather than struct
if any member is non-publicReadability.
To make it clear that something is being hidden/abstracted.
This is a useful convention.
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.
Prefer to place the interface first in a class, see NL.16.
Flag classes declared with struct
if there is a private
or protected
member.
Encapsulation.
Information hiding.
Minimize the chance of unintended access.
This simplifies maintenance.
template
struct pair {
T a;
U b;
// ...
};
Whatever we do in the //
-part, an arbitrary user of a pair
can arbitrarily and independently change its a
and b
.
In a large code base, we cannot easily find which code does what to the members of pair
.
This might be exactly what we want, but if we want to enforce a relation among members, we need to make them private
and enforce that relation (invariant) through constructors and member functions.
For example:
class Distance {
public:
// ...
double meters() const { return magnitude*unit; }
void set_unit(double u)
{
// ... check that u is a factor of 10 ...
// ... change magnitude appropriately ...
unit = u;
}
// ...
private:
double magnitude;
double unit; // 1 is meters, 1000 is kilometers, 0.001 is millimeters, etc.
};
If the set of direct users of a set of variables cannot be easily determined, the type or usage of that set cannot be (easily) changed/improved.
For public
and protected
data, that’s usually the case.
A class can provide two interfaces to its users.
One for derived classes (protected
) and one for general users (public
).
For example, a derived class might be allowed to skip a run-time check because it has already guaranteed correctness:
class Foo {
public:
int bar(int x) { check(x); return do_bar(x); }
// ...
protected:
int do_bar(int x); // do some operation on the data
// ...
private:
// ... data ...
};
class Dir : public Foo {
//...
int mem(int x, int y)
{
/* ... do something ... */
return do_bar(x + y); // OK: derived class can bypass check
}
};
void user(Foo& x)
{
int r1 = x.bar(1); // OK, will check
int r2 = x.do_bar(2); // error: would bypass check
// ...
}
protected
data is a bad idea.
Prefer the order public
members before protected
members before private
members; see NL.16.
public
and private
dataConcrete type rule summary:
const
or references in a copyable or movable typeA concrete type is fundamentally simpler than a type in a class 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.
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(1, 2); // make an object on the free store
auto p22 = p21->clone(); // make a copy
// ...
}
If a class is 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.
Concrete types can be stack-allocated and be members of other classes.
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.
???
Regular types are easier to understand and reason about than types that are not regular (irregularities requires extra effort to understand and use).
The C++ built-in types are regular, and so are standard-library classes such as string
, vector
, and map
. Concrete classes without assignment and equality can be defined, but they are (and should be) rare.
struct Bundle {
string name;
vector 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 is copyable, prefer to also give it an equality comparison operator, and ensure that a = b
implies a == b
.
For structs intended to be shared with C code, defining operator==
may not be feasible.
Handles for resources that cannot be cloned, e.g., a scoped_lock
for a mutex
, are concrete types but typically cannot be copied (instead, they can usually be moved),
so they can’t be regular; instead, they tend to be move-only.
???
const
or references in a copyable or movable typeconst
and reference data members are not useful in a copyable or movable type, and make such types difficult to use by making them at least partly uncopyable/unmovable for subtle reasons.
class bad {
const int i; // bad
string& s; // bad
// ...
};
The const
and &
data members make this class “only-sort-of-copyable” – copy-constructible but not copy-assignable.
If you need a member to point to something, use a pointer (raw or smart, and gsl::not_null
if it should not be null) instead of a reference.
Flag a data member that is const
, &
, or &&
in a type that has any copy or move operation.
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:
X()
X(const X&)
operator=(const X&)
X(X&&)
operator=(X&&)
~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:
=delete
any copy, move, or destructor function, define or =delete
them allDestructor rules:
T*
) or reference (T&
), consider whether it might be owningnoexcept
Constructor rules:
explicit
Copy and move rules:
virtual
, take the parameter by const&
, and return by non-const&
virtual
, take the parameter by &&
, and return by non-const&
noexcept
Other default operations rules:
=default
if you have to be explicit about using the default semantics=delete
when you want to disable default behavior (without wanting an alternative)noexcept
swap functionswap
must not failswap
noexcept
==
symmetric with respect of operand types and noexcept
==
on base classeshash
noexcept
By default, the language supplies the default operations with their default semantics.
However, a programmer can disable or replace these defaults.
It’s the simplest and gives the cleanest semantics.
struct Named_map {
public:
// ... no default operations declared ...
private:
string name;
map 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.
This is known as “the rule of zero”.
(Not enforceable) While not enforceable, a good static analyzer can detect patterns that indicate a possible improvement to meet this rule.
For example, a class with a (pointer, size) pair of members and a destructor that delete
s the pointer could probably be converted to a vector
.
=delete
any copy, move, or destructor function, define or =delete
them allThe semantics of copy, move, and destruction are closely related, so if one needs to be declared, the odds are that others need consideration too.
Declaring any copy/move/destructor function,
even as =default
or =delete
, will suppress the implicit declaration
of a move constructor and move assignment operator.
Declaring a move constructor or move assignment operator, even as
=default
or =delete
, will cause an implicitly generated copy constructor
or implicitly generated copy assignment operator to be defined as deleted.
So as soon as any of these are declared, the others should
all be declared to avoid unwanted effects like turning all potential moves
into more expensive copies, or making a class move-only.
struct M2 { // bad: incomplete set of copy/move/destructor operations
public:
// ...
// ... no copy or move operations ...
~M2() { delete[] rep; }
private:
pair* 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 the implicitly-defined copy and move assignment operators will be correct is low (here, we would get double deletion).
This is known as “the rule of five.”
If you want a default implementation (while defining another), write =default
to show you’re doing so intentionally for that function.
If you don’t want a generated default function, suppress it with =delete
.
When a destructor needs to be declared just to make it virtual
, it can be
defined as defaulted.
class AbstractBase {
public:
virtual void foo() = 0; // at least one abstract method to make the class abstract
virtual ~AbstractBase() = default;
// ...
};
To prevent slicing as per C.67,
make the copy and move operations protected or =delete
d, and add a clone
:
class CloneableBase {
public:
virtual unique_ptr clone() const;
virtual ~CloneableBase() = default;
CloneableBase() = default;
CloneableBase(const CloneableBase&) = delete;
CloneableBase& operator=(const CloneableBase&) = delete;
CloneableBase(CloneableBase&&) = delete;
CloneableBase& operator=(CloneableBase&&) = delete;
// ... other constructors and functions ...
};
Defining only the move operations or only the copy operations would have the
same effect here, but stating the intent explicitly for each special member
makes it more obvious to the reader.
Compilers enforce much of this rule and ideally warn about any violation.
Relying on an implicitly generated copy operation in a class with a destructor is deprecated.
Writing these functions can be error-prone.
Note their argument types:
class X {
public:
// ...
virtual ~X() = default; // destructor (virtual if X is meant to be a base class)
X(const X&) = default; // copy constructor
X& operator=(const X&) = default; // copy assignment
X(X&&) noexcept = default; // move constructor
X& operator=(X&&) noexcept = default; // move assignment
};
A minor mistake (such as a misspelling, leaving out a const
, using &
instead of &&
, or leaving out a special function) can lead to errors or warnings.
To avoid the tedium and the possibility of errors, try to follow the rule of zero.
(Simple) A class should have a declaration (even a =delete
one) for either all or none of the copy/move/destructor functions.
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.
class Silly { // BAD: Inconsistent copy operations
class Impl {
// ...
};
shared_ptr p;
public:
Silly(const Silly& a) : p(make_shared()) { *p = *a.p; } // deep copy
Silly& operator=(const Silly& a) { p = a.p; return *this; } // shallow copy
// ...
};
These operations disagree about copy semantics. This will lead to confusion and bugs.
“Does this class need a destructor?” is a surprisingly insightful 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).
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.
template
struct final_action { // slightly simplified
A act;
final_action(A a) : act{a} {}
~final_action() { act(); }
};
template
final_action finally(A act) // deduce action type
{
return final_action{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.
There are two general categories of classes that need a user-defined destructor:
vector
or a transaction class.final_action
.class Foo { // bad; use the default destructor
public:
// ...
~Foo() { s = ""; i = 0; vi.clear(); } // clean up
private:
string s;
int i;
vector vi;
};
The default destructor does it better, more efficiently, and can’t get it wrong.
If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use =default
.
Look for likely “implicit resources”, such as pointers and references. Look for classes with destructors even though all their data members have destructors.
Prevention of resource leaks, especially in error cases.
For resources represented as classes with a complete set of default operations, this happens automatically.
class X {
ifstream f; // might own a file
// ... no default operations defined or =deleted ...
};
X
’s ifstream
implicitly closes any file it might have open upon destruction of its X
.
class X2 { // bad
FILE* f; // might own a file
// ... no default operations defined or =deleted ...
};
X2
might leak a file handle.
What about a socket 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.
A class can hold pointers and references to objects that it does not own.
Obviously, such objects should not be delete
d by the class’s destructor.
For example:
Preprocessor pp { /* ... */ };
Parser p { pp, /* ... */ };
Type_checker tc { p, /* ... */ };
Here p
refers to pp
but does not own it.
gsl::owner
), then they should be referenced in its destructor.T*
) or reference (T&
), consider whether it might be owningThere is a lot of code that is non-specific about ownership.
class legacy_class
{
foo* m_owning; // Bad: change to unique_ptr or owner
bar* m_observer; // OK: keep
}
The only way to determine ownership may be code analysis.
Ownership should be clear in new code (and refactored legacy code) according to R.20 for owning
pointers and R.3 for non-owning pointers. References should never own R.4.
Look at the initialization of raw member pointers and member references and see if an allocation is used.
An owned object must be deleted
upon destruction of the object that owns it.
A pointer member could 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
class Smart_ptr {
T* p; // BAD: vague about ownership of *p
// ...
public:
// ... no user-defined default operations ...
};
void use(Smart_ptr 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
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 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
class Smart_ptr3 {
owner p; // OK: explicit about ownership of *p
// ...
public:
// ...
// ... copy and move operations ...
~Smart_ptr3() { delete p; }
};
void use(Smart_ptr3 p1)
{
auto p2 = p1; // OK: no double deletion
}
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.
Why not just require all owning pointers to be “smart pointers”?
That would sometimes require non-trivial code changes and might affect ABIs.
owner
should define its default operations.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.
See this in the Discussion section.
struct Base { // BAD: implicitly has a public non-virtual destructor
virtual void f();
};
struct D : Base {
string s {"a resource needing cleanup"};
~D() { /* ... do some cleanup ... */ }
// ...
};
void use()
{
unique_ptr p = make_unique();
// ...
} // p's destruction calls ~Base(), not ~D(), which leaks D::s and possibly more
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.
A destructor must be non-private or it will prevent using the type:
class X {
~X(); // private destructor
// ...
};
void use()
{
X a; // error: cannot destroy
auto p = make_unique(); // error: cannot destroy
}
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.
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.
class X {
public:
~X() noexcept;
// ...
};
X::~X() noexcept
{
// ...
if (cannot_release_a_resource) terminate();
// ...
}
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.
Declare a destructor noexcept
. That will ensure that it either completes normally or terminates the program.
If a resource cannot be released and the program must 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.
If a destructor uses operations that could 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).
(Simple) A destructor should be declared noexcept
if it could throw.
noexcept
A destructor must not fail. If a destructor tries to exit with an exception, it’s a bad design error and the program had better terminate.
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. By explicitly marking destructors noexcept
, an author guards against the destructor becoming implicitly noexcept(false)
through the addition or modification of a class member.
Not all destructors are noexcept by default; one throwing member poisons the whole class hierarchy
struct X {
Details x; // happens to have a throwing destructor
// ...
~X() { } // implicitly noexcept(false); aka can throw
};
So, if in doubt, declare a destructor noexcept.
Why not then declare all destructors noexcept?
Because that would in many cases – especially simple cases – be distracting clutter.
(Simple) A destructor should be declared noexcept
if it could throw.
A constructor defines how an object is initialized (constructed).
That’s what constructors are for.
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.
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"};
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.
A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
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.
If a valid object cannot conveniently be constructed by a constructor, use a factory function.
Ensures
contract, try to see if it holds as a postcondition.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”).
Leaving behind an invalid object is asking for trouble.
class X2 {
FILE* f;
// ...
public:
X2(const string& name)
:f{fopen(name.c_str(), "r")}
{
if (!f) 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
// ...
}
class X3 { // bad: the constructor leaves a non-valid object behind
FILE* f; // call is_valid() 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 ...
}
// ...
}
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.
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.
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.
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 has 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
???
That is, ensure that if a concrete class is copyable it also satisfies the rest of “semiregular.”
Many language and library facilities rely on default constructors to initialize their elements, e.g. T a[10]
and std::vector
.
A default constructor often simplifies the task of defining a suitable moved-from state for a type that is also copyable.
class Date { // BAD: no default constructor
public:
Date(int dd, int mm, int yyyy);
// ...
};
vector vd1(1000); // default Date needed here
vector vd2(1000, Date{7, Month::October, 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.
The absence of a default value can cause surprises for users and complicate its use, so if one can be reasonably defined, it should be.
Date
is chosen to encourage thought:
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.
class Date {
public:
Date(int dd, int mm, int yyyy);
Date() = default; // [See also](#Rc-default)
// ...
private:
int dd {1};
int mm {1};
int yyyy {1970};
// ...
};
vector vd1(1000);
A class with members that all have default constructors implicitly gets a default constructor:
struct X {
string s;
vector 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 might default initialize local built-in variables, whereas an optimized build will not.
Thus, code like the example above might 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)
};
Classes that don’t have a reasonable default construction are usually not copyable either, so they don’t fall under this guideline.
For example, a base class should not be copyable, and so does not necessarily need a default constructor:
// Shape is an abstract base class, not a copyable type.
// It might or might not need a default constructor.
struct Shape {
virtual void draw() = 0;
virtual void rotate(int) = 0;
// =delete copy/move functions
// ...
};
A class that must acquire a caller-provided resource during construction often cannot have a default constructor, but it does not fall under this guideline because such a class is usually not copyable anyway:
// std::lock_guard is not a copyable type.
// It does not have a default constructor.
lock_guard g {mx}; // guard the mutex mx
lock_guard g2; // error: guarding nothing
A class that has a “special state” that must be handled separately from other states by member functions or users causes extra work
(and most likely more errors). Such a type can naturally use the special state as a default constructed value, whether or not it is copyable:
// std::ofstream is not a copyable type.
// It does happen to have a default constructor
// that goes along with a special "not open" state.
ofstream out {"Foobar"};
// ...
out << log(time, transaction);
Similar special-state types that are copyable, such as copyable smart pointers that have the special state “==nullptr”, should use the special state as their default constructed value.
However, it is preferable to have a default constructor default to a meaningful state such as std::string
s ""
and std::vector
s {}
.
=
without a default constructor==
but not copyableBeing able to set a value to “the default” without operations that might fail simplifies error handling and reasoning about move operations.
template
// 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 elem;
T* space;
T* last;
};
This is nice and general, but setting a Vector0
to empty after an error involves an allocation, which might fail.
Also, having a default Vector
represented as {new T[0], 0, 0}
seems wasteful.
For example, Vector0
costs 100 allocations.
template
// 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 elem {};
T* space {};
T* last {};
};
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.
Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
class X1 { // BAD: doesn't use member initializers
string s;
int i;
public:
X1() :s{"default"}, i{1} { }
// ...
};
class X2 {
string s {"default"};
int i {1};
public:
// use compiler-generated default constructor
// ...
};
(Simple) A default constructor should do more than just initialize member variables with constants.
To avoid unintended conversions.
class String {
public:
String(int); // BAD
// ...
};
String s = 10; // surprise: string of size 10
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
Copy and move constructors should not be made explicit
because they do not perform conversions. Explicit copy/move constructors make passing and returning by value difficult.
(Simple) Single-argument constructors should be declared explicit
. Good single argument non-explicit
constructors are rare in most code bases. Warn for all that are not on a “positive list”.
To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).
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
(Simple) A member initializer list should mention the members in the same order they are declared.
See also: Discussion
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.
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 bad 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.
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
// ...
};
An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents “use before set” errors.
class A { // Good
string s1;
public:
A(czstring p) : s1{p} { } // GOOD: directly construct (and the C-string is explicitly named)
// ...
};
class B { // BAD
string s1;
public:
B(const char* p) { s1 = p; } // 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
// ...
};
Instead of those const char*
s we could use C++17 std::string_view
or gsl::span
as a more general way to present arguments to a function:
class D { // Good
string s1;
public:
D(string_view v) : s1{v} { } // GOOD: directly construct
// ...
};
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.
The return type of the factory should normally be unique_ptr
by default; if some uses are shared, the caller can move
the unique_ptr
into a shared_ptr
. However, if the factory author knows that all uses of the returned object will be shared uses, return shared_ptr
and use make_shared
in the body to save an allocation.
class B {
public:
B()
{
/* ... */
f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
/* ... */
}
virtual void f() = 0;
};
class B {
protected:
class Token {};
public:
explicit B(Token) { /* ... */ } // create an imperfectly initialized object
virtual void f() = 0;
template
static shared_ptr create() // interface for creating shared objects
{
auto p = make_shared(typename T::Token{});
p->post_initialize();
return p;
}
protected:
virtual void post_initialize() // called right after construction
{ /* ... */ f(); /* ... */ } // GOOD: virtual dispatch is safe
};
class D : public B { // some derived class
protected:
class Token {};
public:
explicit D(Token) : B{ B::Token{} } {}
void f() override { /* ... */ };
protected:
template
friend shared_ptr B::create();
};
shared_ptr p = D::create(); // creating a D object
make_shared
requires that the constructor is public. By requiring a protected Token
the constructor cannot be publicly called anymore, so we avoid an incompletely constructed object escaping into the wild.
By providing the factory function create()
, we make construction (on the free store) convenient.
Conventional factory functions allocate on the free store, rather than on the stack or in an enclosing object.
See also: Discussion
To avoid repetition and accidental differences.
class Date { // BAD: repetitive
int d;
Month m;
int y;
public:
Date(int dd, Month mm, year yy)
:d{dd}, m{mm}, y{yy}
{ if (!valid(d, m, y)) throw Bad_date{}; }
Date(int dd, Month mm)
:d{dd}, m{mm} y{current_year()}
{ if (!valid(d, m, y)) throw Bad_date{}; }
// ...
};
The common action gets tedious to write and might accidentally not be common.
class Date2 {
int d;
Month m;
int y;
public:
Date2(int dd, Month mm, year yy)
:d{dd}, m{mm}, y{yy}
{ if (!valid(d, m, y)) throw Bad_date{}; }
Date2(int dd, Month mm)
:Date2{dd, mm, current_year()} {}
// ...
};
See also: If the “repeated action” is a simple initialization, consider an in-class member initializer.
(Moderate) Look for similar constructor bodies.
If you need those constructors for a derived class, re-implementing them is tedious and error-prone.
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 ...
};
struct Rec2 : public Rec {
int x;
using Rec::Rec;
};
Rec2 r {"foo", 7};
int val = r.x; // uninitialized
Make sure that every member of the derived class is initialized.
Concrete types should generally be copyable, but interfaces in a class hierarchy should not.
Resource handles might or might not be copyable.
Types can be defined to move for logical as well as performance reasons.
virtual
, take the parameter by const&
, and return by non-const&
It is simple and efficient. If you want to optimize for rvalues, provide an overload that takes a &&
(see F.18).
class Foo {
public:
Foo& operator=(const Foo& x)
{
// GOOD: no need to check for self-assignment (other than performance)
auto tmp = x;
swap(tmp); // see C.83
return *this;
}
// ...
};
Foo a;
Foo b;
Foo f();
a = b; // assign lvalue: copy
a = f(); // assign rvalue: potentially move
The swap
implementation technique offers the strong guarantee.
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 Vector
s is common. In this case, the copy of elements implied by the swap
implementation technique could cause an order of magnitude increase in cost:
template
class Vector {
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()
.
T&
to enable chaining, not alternatives like const T&
which interfere with composability and putting objects in containers.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).
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, p);
}
X x;
X y = x;
if (x != y) throw Bad{};
x.modify();
if (x == y) throw Bad{}; // assume value semantics
class X2 { // OK: pointer semantics
public:
X2();
X2(const X2&) = default; // shallow copy
~X2() = default;
void modify(); // change the pointed-to value
// ...
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
Prefer value semantics unless you are building a “smart pointer”. Value semantics is the simplest to reason about and what the standard-library facilities expect.
(Not enforceable)
If x = x
changes the value of x
, people will be surprised and bad errors will occur (often including leaks).
The standard-library containers handle self-assignment elegantly and efficiently:
std::vector v = {3, 1, 4, 1, 5, 9};
v = v;
// the value of v is still {3, 1, 4, 1, 5, 9}
The default assignment generated from members that handle self-assignment correctly handles self-assignment.
struct Bar {
vector> v;
map m;
string s;
};
Bar b;
// ...
b = b; // correct and efficient
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.
(Simple) Assignment operators should not contain the pattern if (this == &a) return *this;
???
virtual
, take the parameter by &&
, and return by non-const&
It is simple and efficient.
See: The rule for copy-assignment.
Equivalent to what is done for copy-assignment.
T&
to enable chaining, not alternatives like const T&
which interfere with composability and putting objects in containers.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.
class X { // OK: value semantics
public:
X();
X(X&& a) noexcept; // move X
X& operator=(X&& a) noexcept; // move-assign X
void modify(); // change the value of X
// ...
~X() { delete[] p; }
private:
T* p;
int sz;
};
X::X(X&& a) noexcept
: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
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 is possible to assign to a moved-from object.
Always leave the moved-from object in some (necessarily specified) valid state.
Unless there is an exceptionally strong reason not to, make x = std::move(y); y = z;
work with the conventional semantics.
(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.
If x = x
changes the value of x
, people will be surprised and bad errors can 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.
class Foo {
string s;
int i;
public:
Foo& operator=(Foo&& a) noexcept;
// ...
};
Foo& Foo::operator=(Foo&& a) noexcept // 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.
There is no known general way of avoiding an 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).
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.
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; // in self-move, this->ptr is also null; delete is a no-op
ptr = temp; // in self-move, the original ptr is restored
delete
d or set to nullptr
.string
) and consider them safe for ordinary (not life-critical) uses.noexcept
A throwing move violates most people’s reasonable assumptions.
A non-throwing move will be used more efficiently by standard-library and language facilities.
template
class Vector {
public:
Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.elem = nullptr; a.sz = 0; }
Vector& operator=(Vector&& a) noexcept {
delete elem;
elem = a.elem; a.elem = nullptr;
sz = a.sz; a.sz = 0;
return *this;
}
// ...
private:
T* elem;
int sz;
};
These operations do not throw.
template
class Vector2 {
public:
Vector2(Vector2&& a) noexcept { *this = a; } // just use the copy
Vector2& operator=(Vector2&& a) noexcept { *this = a; } // just use the copy
// ...
private:
T* elem;
int sz;
};
This Vector2
is not just inefficient, but since a vector copy requires allocation, it can throw.
(Simple) A move operation should be marked noexcept
.
A polymorphic class is a class that defines or inherits at least one virtual function. It is likely that it will be used as a base class for other derived classes with polymorphic behavior. If it is accidentally passed by value, with the implicitly generated copy constructor and assignment, we risk slicing: only the base portion of a derived object will be copied, and the polymorphic behavior will be corrupted.
If the class has no data, =delete
the copy/move functions. Otherwise, make them protected.
class B { // BAD: polymorphic base class doesn't suppress copying
public:
virtual char m() { return 'B'; }
// ... nothing about copy operations, so uses default ...
};
class D : public B {
public:
char m() override { return 'D'; }
// ...
};
void f(B& b)
{
auto b2 = b; // oops, slices the object; b2.m() will return 'B'
}
D d;
f(d);
class B { // GOOD: polymorphic class suppresses copying
public:
B() = default;
B(const B&) = delete;
B& operator=(const B&) = delete;
virtual char m() { return 'B'; }
// ...
};
class D : public B {
public:
char m() override { return 'D'; }
// ...
};
void f(B& b)
{
auto b2 = b; // ok, compiler will detect inadvertent copying, and protest
}
D d;
f(d);
If you need to create deep copies of polymorphic objects, use clone()
functions: see C.130.
Classes that represent exception objects need both to be polymorphic and copy-constructible.
In addition to the operations for which the language offers default implementations,
there are a few operations that are so foundational that specific rules for their definition are needed:
comparisons, swap
, and hash
.
=default
if you have to be explicit about using the default semanticsThe compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.
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&&) noexcept = default;
Tracer& operator=(Tracer&&) noexcept = 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.
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) noexcept :message{a.message} {}
Tracer2& operator=(Tracer2&& a) noexcept { 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.
(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
=delete
when you want to disable default behavior (without wanting an alternative)In a few cases, a default operation is not desirable.
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
}
A unique_ptr
can be moved, but not copied. To achieve that its copy operations are deleted. To avoid copying it is necessary to =delete
its copy operations from lvalues:
template> class unique_ptr {
public:
// ...
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 make(); // make "something" and return it by moving
void f()
{
unique_ptr pi {};
auto pi2 {pi}; // error: no move constructor from lvalue
auto pi3 {make()}; // OK, move: the result of make() is an rvalue
}
Note that deleted functions should be public.
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.
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.
class Base {
public:
virtual void f() = 0; // not implemented
virtual void g(); // implemented with Base version
virtual void h(); // implemented with Base version
virtual ~Base(); // 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.
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.
noexcept
swap functionA 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.
class Foo {
public:
void swap(Foo& rhs) noexcept
{
m1.swap(rhs.m1);
std::swap(m2, rhs.m2);
}
private:
Bar m1;
int m2;
};
Providing a non-member swap
function in the same namespace as your type for callers’ convenience.
void swap(Foo& a, Foo& b)
{
a.swap(b);
}
swap
member function, it should be declared noexcept
.swap
function must not failswap
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.
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
could throw and would make STL algorithms fail if used with them.
(Simple) When a class has a swap
member function, it should be declared noexcept
.
swap
noexcept
A swap
must not fail.
If a swap
tries to exit with an exception, it’s a bad design error and the program had better terminate.
(Simple) When a class has a swap
member function, it should be declared noexcept
.
==
symmetric with respect to operand types and noexcept
Asymmetric treatment of operands is surprising and a source of errors where conversions are possible.
==
is a fundamental operation and programmers should be able to use it without fear of failure.
struct X {
string name;
int number;
};
bool operator==(const X& a, const X& b) noexcept {
return a.name == b.name && a.number == b.number;
}
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.
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.
This rule