mirror of
https://github.com/isocpp/CppCoreGuidelines.git
synced 2025-12-17 20:54:41 +03:00
Adjust the spacing for consistency (#1626)
* Adjust the spacing for consistency * Adjust the spacing for consistency-2
This commit is contained in:
@@ -1778,7 +1778,7 @@ This is a major source of errors.
|
|||||||
|
|
||||||
int printf(const char* ...); // bad: return negative number if output fails
|
int printf(const char* ...); // bad: return negative number if output fails
|
||||||
|
|
||||||
template <class F, class ...Args>
|
template<class F, class ...Args>
|
||||||
// good: throw system_error if unable to start the new thread
|
// good: throw system_error if unable to start the new thread
|
||||||
explicit thread(F&& f, Args&&... args);
|
explicit thread(F&& f, Args&&... args);
|
||||||
|
|
||||||
@@ -2299,10 +2299,10 @@ So, we write a class
|
|||||||
public:
|
public:
|
||||||
enum Opt { from_line = 1 };
|
enum Opt { from_line = 1 };
|
||||||
Istream() { }
|
Istream() { }
|
||||||
Istream(zstring p) :owned{true}, inp{new ifstream{p}} {} // read from file
|
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(zstring p, Opt) : owned{true}, inp{new istringstream{p}} {} // read from command line
|
||||||
~Istream() { if (owned) delete inp; }
|
~Istream() { if (owned) delete inp; }
|
||||||
operator istream& () { return *inp; }
|
operator istream&() { return *inp; }
|
||||||
private:
|
private:
|
||||||
bool owned = false;
|
bool owned = false;
|
||||||
istream* inp = &cin;
|
istream* inp = &cin;
|
||||||
@@ -2958,7 +2958,8 @@ It's efficient and eliminates bugs at the call site: `X&&` binds to rvalues, whi
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
void sink(vector<int>&& v) { // sink takes ownership of whatever the argument owned
|
void sink(vector<int>&& v) // sink takes ownership of whatever the argument owned
|
||||||
|
{
|
||||||
// usually there might be const accesses of v here
|
// usually there might be const accesses of v here
|
||||||
store_somewhere(std::move(v));
|
store_somewhere(std::move(v));
|
||||||
// usually no more use of v here; it is moved-from
|
// usually no more use of v here; it is moved-from
|
||||||
@@ -2974,8 +2975,9 @@ Unique owner types that are move-only and cheap-to-move, such as `unique_ptr`, c
|
|||||||
|
|
||||||
For example:
|
For example:
|
||||||
|
|
||||||
template <class T>
|
template<class T>
|
||||||
void sink(std::unique_ptr<T> p) {
|
void sink(std::unique_ptr<T> p)
|
||||||
|
{
|
||||||
// use p ... possibly std::move(p) onward somewhere else
|
// use p ... possibly std::move(p) onward somewhere else
|
||||||
} // p gets destroyed
|
} // p gets destroyed
|
||||||
|
|
||||||
@@ -2995,8 +2997,9 @@ In that case, and only that case, make the parameter `TP&&` where `TP` is a temp
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
template <class F, class... Args>
|
template<class F, class... Args>
|
||||||
inline auto invoke(F f, Args&&... args) {
|
inline auto invoke(F f, Args&&... args)
|
||||||
|
{
|
||||||
return f(forward<Args>(args)...);
|
return f(forward<Args>(args)...);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3722,7 +3725,8 @@ This was primarily to avoid code of the form `(a = b) = c` -- such code is not c
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
...
|
...
|
||||||
Foo& operator=(const Foo& rhs) {
|
Foo& operator=(const Foo& rhs)
|
||||||
|
{
|
||||||
// Copy members.
|
// Copy members.
|
||||||
...
|
...
|
||||||
return *this;
|
return *this;
|
||||||
@@ -3779,7 +3783,7 @@ Functions can't capture local variables or be defined at local scope; if you nee
|
|||||||
// at statement or expression scope -- a lambda is natural
|
// at statement or expression scope -- a lambda is natural
|
||||||
vector<work> v = lots_of_work();
|
vector<work> v = lots_of_work();
|
||||||
for (int tasknum = 0; tasknum < max; ++tasknum) {
|
for (int tasknum = 0; tasknum < max; ++tasknum) {
|
||||||
pool.run([=, &v]{
|
pool.run([=, &v] {
|
||||||
/*
|
/*
|
||||||
...
|
...
|
||||||
... process 1 / max - th of v, the tasknum - th chunk
|
... process 1 / max - th of v, the tasknum - th chunk
|
||||||
@@ -3795,7 +3799,7 @@ Generic lambdas offer a concise way to write function templates and so can be us
|
|||||||
|
|
||||||
##### Enforcement
|
##### Enforcement
|
||||||
|
|
||||||
* Warn on use of a named non-generic lambda (e.g., `auto x = [](int i){ /*...*/; };`) that captures nothing and appears at global scope. Write an ordinary function instead.
|
* Warn on use of a named non-generic lambda (e.g., `auto x = [](int i) { /*...*/; };`) that captures nothing and appears at global scope. Write an ordinary function instead.
|
||||||
|
|
||||||
### <a name="Rf-default-args"></a>F.51: Where there is a choice, prefer default arguments over overloading
|
### <a name="Rf-default-args"></a>F.51: Where there is a choice, prefer default arguments over overloading
|
||||||
|
|
||||||
@@ -3863,9 +3867,9 @@ This is a simple three-stage parallel pipeline. Each `stage` object encapsulates
|
|||||||
|
|
||||||
void send_packets(buffers& bufs)
|
void send_packets(buffers& bufs)
|
||||||
{
|
{
|
||||||
stage encryptor([] (buffer& b){ encrypt(b); });
|
stage encryptor([](buffer& b) { encrypt(b); });
|
||||||
stage compressor([&](buffer& b){ compress(b); encryptor.process(b); });
|
stage compressor([&](buffer& b) { compress(b); encryptor.process(b); });
|
||||||
stage decorator([&](buffer& b){ decorate(b); compressor.process(b); });
|
stage decorator([&](buffer& b) { decorate(b); compressor.process(b); });
|
||||||
for (auto& b : bufs) { decorator.process(b); }
|
for (auto& b : bufs) { decorator.process(b); }
|
||||||
} // automatically blocks waiting for pipeline to finish
|
} // automatically blocks waiting for pipeline to finish
|
||||||
|
|
||||||
@@ -3887,7 +3891,7 @@ Pointers and references to locals shouldn't outlive their scope. Lambdas that ca
|
|||||||
// Note, that after program exits this scope,
|
// Note, that after program exits this scope,
|
||||||
// local no longer exists, therefore
|
// local no longer exists, therefore
|
||||||
// process() call will have undefined behavior!
|
// process() call will have undefined behavior!
|
||||||
thread_pool.queue_work([&]{ process(local); });
|
thread_pool.queue_work([&] { process(local); });
|
||||||
|
|
||||||
##### Example, good
|
##### Example, good
|
||||||
|
|
||||||
@@ -3895,7 +3899,7 @@ Pointers and references to locals shouldn't outlive their scope. Lambdas that ca
|
|||||||
// Want a copy of local.
|
// Want a copy of local.
|
||||||
// Since a copy of local is made, it will
|
// Since a copy of local is made, it will
|
||||||
// always be available for the call.
|
// always be available for the call.
|
||||||
thread_pool.queue_work([=]{ process(local); });
|
thread_pool.queue_work([=] { process(local); });
|
||||||
|
|
||||||
##### Enforcement
|
##### Enforcement
|
||||||
|
|
||||||
@@ -3914,11 +3918,12 @@ It's confusing. Writing `[=]` in a member function appears to capture by value,
|
|||||||
int x = 0;
|
int x = 0;
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
void f() {
|
void f()
|
||||||
|
{
|
||||||
int i = 0;
|
int i = 0;
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
auto lambda = [=]{ use(i, x); }; // BAD: "looks like" copy/value capture
|
auto lambda = [=] { use(i, x); }; // BAD: "looks like" copy/value capture
|
||||||
// [&] has identical semantics and copies the this pointer under the current rules
|
// [&] has identical semantics and copies the this pointer under the current rules
|
||||||
// [=,this] and [&,this] are not much better, and confusing
|
// [=,this] and [&,this] are not much better, and confusing
|
||||||
|
|
||||||
@@ -3929,7 +3934,7 @@ It's confusing. Writing `[=]` in a member function appears to capture by value,
|
|||||||
|
|
||||||
// ...
|
// ...
|
||||||
|
|
||||||
auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing
|
auto lambda2 = [i, this] { use(i, x); }; // ok, most explicit and least confusing
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
@@ -3953,7 +3958,8 @@ This is fragile because it cannot generally be enforced to be safe in the langua
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
int sum(...) {
|
int sum(...)
|
||||||
|
{
|
||||||
// ...
|
// ...
|
||||||
while (/*...*/)
|
while (/*...*/)
|
||||||
result += va_arg(list, int); // BAD, assumes it will be passed ints
|
result += va_arg(list, int); // BAD, assumes it will be passed ints
|
||||||
@@ -3964,7 +3970,8 @@ This is fragile because it cannot generally be enforced to be safe in the langua
|
|||||||
sum(3.14159, 2.71828); // BAD, undefined
|
sum(3.14159, 2.71828); // BAD, undefined
|
||||||
|
|
||||||
template<class ...Args>
|
template<class ...Args>
|
||||||
auto sum(Args... args) { // GOOD, and much more flexible
|
auto sum(Args... args) // GOOD, and much more flexible
|
||||||
|
{
|
||||||
return (... + args); // note: C++17 "fold expression"
|
return (... + args); // note: C++17 "fold expression"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4735,7 +4742,7 @@ Only define a non-default destructor if a class needs to execute code that is no
|
|||||||
template<typename A>
|
template<typename A>
|
||||||
struct final_action { // slightly simplified
|
struct final_action { // slightly simplified
|
||||||
A act;
|
A act;
|
||||||
final_action(A a) :act{a} {}
|
final_action(A a) : act{a} {}
|
||||||
~final_action() { act(); }
|
~final_action() { act(); }
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -4747,7 +4754,7 @@ Only define a non-default destructor if a class needs to execute code that is no
|
|||||||
|
|
||||||
void test()
|
void test()
|
||||||
{
|
{
|
||||||
auto act = finally([]{ cout << "Exit test\n"; }); // establish exit action
|
auto act = finally([] { cout << "Exit test\n"; }); // establish exit action
|
||||||
// ...
|
// ...
|
||||||
if (something) return; // act done here
|
if (something) return; // act done here
|
||||||
// ...
|
// ...
|
||||||
@@ -5642,7 +5649,8 @@ The return type of the factory should normally be `unique_ptr` by default; if so
|
|||||||
|
|
||||||
class B {
|
class B {
|
||||||
public:
|
public:
|
||||||
B() {
|
B()
|
||||||
|
{
|
||||||
/* ... */
|
/* ... */
|
||||||
f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
|
f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
|
||||||
/* ... */
|
/* ... */
|
||||||
@@ -6173,7 +6181,8 @@ A *polymorphic class* is a class that defines or inherits at least one virtual f
|
|||||||
// ...
|
// ...
|
||||||
};
|
};
|
||||||
|
|
||||||
void f(B& b) {
|
void f(B& b)
|
||||||
|
{
|
||||||
auto b2 = b; // oops, slices the object; b2.m() will return 'B'
|
auto b2 = b; // oops, slices the object; b2.m() will return 'B'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6196,7 +6205,8 @@ A *polymorphic class* is a class that defines or inherits at least one virtual f
|
|||||||
// ...
|
// ...
|
||||||
};
|
};
|
||||||
|
|
||||||
void f(B& b) {
|
void f(B& b)
|
||||||
|
{
|
||||||
auto b2 = b; // ok, compiler will detect inadvertent copying, and protest
|
auto b2 = b; // ok, compiler will detect inadvertent copying, and protest
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6289,7 +6299,7 @@ In a few cases, a default operation is not desirable.
|
|||||||
|
|
||||||
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:
|
A `unique_ptr` can be moved, but not copied. To achieve that its copy operations are deleted. To avoid copying it is necessary to `=delete` its copy operations from lvalues:
|
||||||
|
|
||||||
template <class T, class D = default_delete<T>> class unique_ptr {
|
template<class T, class D = default_delete<T>> class unique_ptr {
|
||||||
public:
|
public:
|
||||||
// ...
|
// ...
|
||||||
constexpr unique_ptr() noexcept;
|
constexpr unique_ptr() noexcept;
|
||||||
@@ -6498,7 +6508,7 @@ It is really hard to write a foolproof and useful `==` for a hierarchy.
|
|||||||
|
|
||||||
`B`'s comparison accepts conversions for its second operand, but not its first.
|
`B`'s comparison accepts conversions for its second operand, but not its first.
|
||||||
|
|
||||||
class D :B {
|
class D : B {
|
||||||
char character;
|
char character;
|
||||||
virtual bool operator==(const D& a) const
|
virtual bool operator==(const D& a) const
|
||||||
{
|
{
|
||||||
@@ -6572,14 +6582,12 @@ A type will provide a copy constructor and/or copy assignment operator to approp
|
|||||||
|
|
||||||
##### Example, good
|
##### Example, good
|
||||||
|
|
||||||
struct base
|
struct base {
|
||||||
{
|
|
||||||
virtual void update() = 0;
|
virtual void update() = 0;
|
||||||
std::shared_ptr<int> sp;
|
std::shared_ptr<int> sp;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct derived : public base
|
struct derived : public base {
|
||||||
{
|
|
||||||
void update() override {}
|
void update() override {}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -7137,7 +7145,7 @@ The importance of keeping the two kinds of inheritance increases
|
|||||||
|
|
||||||
class Circle : public Shape {
|
class Circle : public Shape {
|
||||||
public:
|
public:
|
||||||
Circle(Point c, int r) :Shape{c}, rad{r} { /* ... */ }
|
Circle(Point c, int r) : Shape{c}, rad{r} { /* ... */ }
|
||||||
|
|
||||||
// ...
|
// ...
|
||||||
private:
|
private:
|
||||||
@@ -7183,7 +7191,7 @@ Note that a pure interface rarely has constructors: there is nothing to construc
|
|||||||
|
|
||||||
class Circle : public Shape {
|
class Circle : public Shape {
|
||||||
public:
|
public:
|
||||||
Circle(Point c, int r, Color c) :cent{c}, rad{r}, col{c} { /* ... */ }
|
Circle(Point c, int r, Color c) : cent{c}, rad{r}, col{c} { /* ... */ }
|
||||||
|
|
||||||
Point center() const override { return cent; }
|
Point center() const override { return cent; }
|
||||||
Color color() const override { return col; }
|
Color color() const override { return col; }
|
||||||
@@ -7638,7 +7646,7 @@ This issue affects both virtual and non-virtual member functions
|
|||||||
|
|
||||||
For variadic bases, C++17 introduced a variadic form of the using-declaration,
|
For variadic bases, C++17 introduced a variadic form of the using-declaration,
|
||||||
|
|
||||||
template <class... Ts>
|
template<class... Ts>
|
||||||
struct Overloader : Ts... {
|
struct Overloader : Ts... {
|
||||||
using Ts::operator()...; // exposes operator() from every base
|
using Ts::operator()...; // exposes operator() from every base
|
||||||
};
|
};
|
||||||
@@ -8015,7 +8023,8 @@ It also gives an opportunity to eliminate a separate allocation for the referenc
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
void test() {
|
void test()
|
||||||
|
{
|
||||||
// OK: but repetitive; and separate allocations for the Bar and shared_ptr's use count
|
// OK: but repetitive; and separate allocations for the Bar and shared_ptr's use count
|
||||||
shared_ptr<Bar> p {new Bar{7}};
|
shared_ptr<Bar> p {new Bar{7}};
|
||||||
|
|
||||||
@@ -8294,7 +8303,7 @@ Many parts of the C++ semantics assumes its default meaning.
|
|||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
class Ptr { // a somewhat smart pointer
|
class Ptr { // a somewhat smart pointer
|
||||||
Ptr(X* pp) :p(pp) { /* check */ }
|
Ptr(X* pp) : p(pp) { /* check */ }
|
||||||
X* operator->() { /* check */ return p; }
|
X* operator->() { /* check */ return p; }
|
||||||
X operator[](int i);
|
X operator[](int i);
|
||||||
X operator*();
|
X operator*();
|
||||||
@@ -9582,8 +9591,7 @@ be able to destroy a cyclic structure.
|
|||||||
|
|
||||||
class bar;
|
class bar;
|
||||||
|
|
||||||
class foo
|
class foo {
|
||||||
{
|
|
||||||
public:
|
public:
|
||||||
explicit foo(const std::shared_ptr<bar>& forward_reference)
|
explicit foo(const std::shared_ptr<bar>& forward_reference)
|
||||||
: forward_reference_(forward_reference)
|
: forward_reference_(forward_reference)
|
||||||
@@ -9592,8 +9600,7 @@ be able to destroy a cyclic structure.
|
|||||||
std::shared_ptr<bar> forward_reference_;
|
std::shared_ptr<bar> forward_reference_;
|
||||||
};
|
};
|
||||||
|
|
||||||
class bar
|
class bar {
|
||||||
{
|
|
||||||
public:
|
public:
|
||||||
explicit bar(const std::weak_ptr<foo>& back_reference)
|
explicit bar(const std::weak_ptr<foo>& back_reference)
|
||||||
: back_reference_(back_reference)
|
: back_reference_(back_reference)
|
||||||
@@ -10289,7 +10296,7 @@ A structured binding (C++17) is specifically designed to introduce several varia
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
template <class InputIterator, class Predicate>
|
template<class InputIterator, class Predicate>
|
||||||
bool any_of(InputIterator first, InputIterator last, Predicate pred);
|
bool any_of(InputIterator first, InputIterator last, Predicate pred);
|
||||||
|
|
||||||
or better using concepts:
|
or better using concepts:
|
||||||
@@ -10337,7 +10344,7 @@ Consider:
|
|||||||
auto p = v.begin(); // vector<int>::iterator
|
auto p = v.begin(); // vector<int>::iterator
|
||||||
auto h = t.future();
|
auto h = t.future();
|
||||||
auto q = make_unique<int[]>(s);
|
auto q = make_unique<int[]>(s);
|
||||||
auto f = [](int x){ return x + 10; };
|
auto f = [](int x) { return x + 10; };
|
||||||
|
|
||||||
In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
|
In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
|
||||||
|
|
||||||
@@ -10534,7 +10541,7 @@ Assuming that there is a logical connection between `i` and `j`, that connection
|
|||||||
If the `make_related_widgets` function is otherwise redundant,
|
If the `make_related_widgets` function is otherwise redundant,
|
||||||
we can eliminate it by using a lambda [ES.28](#Res-lambda-init):
|
we can eliminate it by using a lambda [ES.28](#Res-lambda-init):
|
||||||
|
|
||||||
auto [i, j] = [x]{ return (x) ? pair{f1(), f2()} : pair{f3(), f4()} }(); // C++17
|
auto [i, j] = [x] { return (x) ? pair{f1(), f2()} : pair{f3(), f4()} }(); // C++17
|
||||||
|
|
||||||
Using a value representing "uninitialized" is a symptom of a problem and not a solution:
|
Using a value representing "uninitialized" is a symptom of a problem and not a solution:
|
||||||
|
|
||||||
@@ -10877,10 +10884,10 @@ Readability and safety.
|
|||||||
|
|
||||||
As an optimization, you may want to reuse a buffer as a scratch pad, but even then prefer to limit the variable's scope as much as possible and be careful not to cause bugs from data left in a recycled buffer as this is a common source of security bugs.
|
As an optimization, you may want to reuse a buffer as a scratch pad, but even then prefer to limit the variable's scope as much as possible and be careful not to cause bugs from data left in a recycled buffer as this is a common source of security bugs.
|
||||||
|
|
||||||
void write_to_file() {
|
void write_to_file()
|
||||||
std::string buffer; // to avoid reallocations on every loop iteration
|
|
||||||
for (auto& o : objects)
|
|
||||||
{
|
{
|
||||||
|
std::string buffer; // to avoid reallocations on every loop iteration
|
||||||
|
for (auto& o : objects) {
|
||||||
// First part of the work.
|
// First part of the work.
|
||||||
generate_first_string(buffer, o);
|
generate_first_string(buffer, o);
|
||||||
write_to_file(buffer);
|
write_to_file(buffer);
|
||||||
@@ -10957,7 +10964,7 @@ It nicely encapsulates local initialization, including cleaning up scratch varia
|
|||||||
|
|
||||||
##### Example, good
|
##### Example, good
|
||||||
|
|
||||||
const widget x = [&]{
|
const widget x = [&] {
|
||||||
widget val; // assume that widget has a default constructor
|
widget val; // assume that widget has a default constructor
|
||||||
for (auto i = 2; i <= N; ++i) { // this could be some
|
for (auto i = 2; i <= N; ++i) { // this could be some
|
||||||
val += some_obj.do_something_with(i); // arbitrarily long code
|
val += some_obj.do_something_with(i); // arbitrarily long code
|
||||||
@@ -10967,7 +10974,7 @@ It nicely encapsulates local initialization, including cleaning up scratch varia
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
string var = [&]{
|
string var = [&] {
|
||||||
if (!in) return ""; // default
|
if (!in) return ""; // default
|
||||||
string s;
|
string s;
|
||||||
for (char c : in >> c)
|
for (char c : in >> c)
|
||||||
@@ -11161,7 +11168,7 @@ Requires messy cast-and-macro-laden code to get working right.
|
|||||||
std::exit(severity);
|
std::exit(severity);
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T, typename... Ts>
|
template<typename T, typename... Ts>
|
||||||
constexpr void error(int severity, T head, Ts... tail)
|
constexpr void error(int severity, T head, Ts... tail)
|
||||||
{
|
{
|
||||||
std::cerr << head;
|
std::cerr << head;
|
||||||
@@ -11804,11 +11811,13 @@ Sometimes, you may be tempted to resort to `const_cast` to avoid code duplicatio
|
|||||||
class Foo {
|
class Foo {
|
||||||
public:
|
public:
|
||||||
// BAD, duplicates logic
|
// BAD, duplicates logic
|
||||||
Bar& get_bar() {
|
Bar& get_bar()
|
||||||
|
{
|
||||||
/* complex logic around getting a non-const reference to my_bar */
|
/* complex logic around getting a non-const reference to my_bar */
|
||||||
}
|
}
|
||||||
|
|
||||||
const Bar& get_bar() const {
|
const Bar& get_bar() const
|
||||||
|
{
|
||||||
/* same complex logic around getting a const reference to my_bar */
|
/* same complex logic around getting a const reference to my_bar */
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
@@ -11820,10 +11829,12 @@ Instead, prefer to share implementations. Normally, you can just have the non-`c
|
|||||||
class Foo {
|
class Foo {
|
||||||
public:
|
public:
|
||||||
// not great, non-const calls const version but resorts to const_cast
|
// not great, non-const calls const version but resorts to const_cast
|
||||||
Bar& get_bar() {
|
Bar& get_bar()
|
||||||
|
{
|
||||||
return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());
|
return const_cast<Bar&>(static_cast<const Foo&>(*this).get_bar());
|
||||||
}
|
}
|
||||||
const Bar& get_bar() const {
|
const Bar& get_bar() const
|
||||||
|
{
|
||||||
/* the complex logic around getting a const reference to my_bar */
|
/* the complex logic around getting a const reference to my_bar */
|
||||||
}
|
}
|
||||||
private:
|
private:
|
||||||
@@ -12002,7 +12013,8 @@ Explicit `move` is needed to explicitly move an object to another scope, notably
|
|||||||
Usually, a `std::move()` is used as an argument to a `&&` parameter.
|
Usually, a `std::move()` is used as an argument to a `&&` parameter.
|
||||||
And after you do that, assume the object has been moved from (see [C.64](#Rc-move-semantic)) and don't read its state again until you first set it to a new value.
|
And after you do that, assume the object has been moved from (see [C.64](#Rc-move-semantic)) and don't read its state again until you first set it to a new value.
|
||||||
|
|
||||||
void f() {
|
void f()
|
||||||
|
{
|
||||||
string s1 = "supercalifragilisticexpialidocious";
|
string s1 = "supercalifragilisticexpialidocious";
|
||||||
|
|
||||||
string s2 = s1; // ok, takes a copy
|
string s2 = s1; // ok, takes a copy
|
||||||
@@ -12019,7 +12031,8 @@ And after you do that, assume the object has been moved from (see [C.64](#Rc-mov
|
|||||||
|
|
||||||
void sink(unique_ptr<widget> p); // pass ownership of p to sink()
|
void sink(unique_ptr<widget> p); // pass ownership of p to sink()
|
||||||
|
|
||||||
void f() {
|
void f()
|
||||||
|
{
|
||||||
auto w = make_unique<widget>();
|
auto w = make_unique<widget>();
|
||||||
// ...
|
// ...
|
||||||
sink(std::move(w)); // ok, give to sink()
|
sink(std::move(w)); // ok, give to sink()
|
||||||
@@ -12039,7 +12052,8 @@ Never write `std::move()` on a const object, it is silently transformed into a c
|
|||||||
|
|
||||||
##### Example, bad
|
##### Example, bad
|
||||||
|
|
||||||
vector<int> make_vector() {
|
vector<int> make_vector()
|
||||||
|
{
|
||||||
vector<int> result;
|
vector<int> result;
|
||||||
// ... load result with data
|
// ... load result with data
|
||||||
return std::move(result); // bad; just write "return result;"
|
return std::move(result); // bad; just write "return result;"
|
||||||
@@ -12058,14 +12072,16 @@ The language already knows that a returned value is a temporary object that can
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
void mover(X&& x) {
|
void mover(X&& x)
|
||||||
|
{
|
||||||
call_something(std::move(x)); // ok
|
call_something(std::move(x)); // ok
|
||||||
call_something(std::forward<X>(x)); // bad, don't std::forward an rvalue reference
|
call_something(std::forward<X>(x)); // bad, don't std::forward an rvalue reference
|
||||||
call_something(x); // suspicious, why not std::move?
|
call_something(x); // suspicious, why not std::move?
|
||||||
}
|
}
|
||||||
|
|
||||||
template<class T>
|
template<class T>
|
||||||
void forwarder(T&& t) {
|
void forwarder(T&& t)
|
||||||
|
{
|
||||||
call_something(std::move(t)); // bad, don't std::move a forwarding reference
|
call_something(std::move(t)); // bad, don't std::move a forwarding reference
|
||||||
call_something(std::forward<T>(t)); // ok
|
call_something(std::forward<T>(t)); // ok
|
||||||
call_something(t); // suspicious, why not std::forward?
|
call_something(t); // suspicious, why not std::forward?
|
||||||
@@ -12174,7 +12190,8 @@ In the rare cases where the slicing was deliberate the code can be surprising.
|
|||||||
Shape s {c}; // copy construct only the Shape part of Circle
|
Shape s {c}; // copy construct only the Shape part of Circle
|
||||||
s = c; // or copy assign only the Shape part of Circle
|
s = c; // or copy assign only the Shape part of Circle
|
||||||
|
|
||||||
void assign(const Shape& src, Shape& dest) {
|
void assign(const Shape& src, Shape& dest)
|
||||||
|
{
|
||||||
dest = src;
|
dest = src;
|
||||||
}
|
}
|
||||||
Circle c2 {{1, 1}, 43};
|
Circle c2 {{1, 1}, 43};
|
||||||
@@ -12696,7 +12713,7 @@ consider `gsl::finally()` as a cleaner and more reliable alternative to `goto ex
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
switch(x){
|
switch(x) {
|
||||||
case 1 :
|
case 1 :
|
||||||
while (/* some condition */) {
|
while (/* some condition */) {
|
||||||
//...
|
//...
|
||||||
@@ -12712,7 +12729,8 @@ consider `gsl::finally()` as a cleaner and more reliable alternative to `goto ex
|
|||||||
Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
|
Often, a loop that requires a `break` is a good candidate for a function (algorithm), in which case the `break` becomes a `return`.
|
||||||
|
|
||||||
//Original code: break inside loop
|
//Original code: break inside loop
|
||||||
void use1(){
|
void use1()
|
||||||
|
{
|
||||||
std::vector<T> vec = {/* initialized with some values */};
|
std::vector<T> vec = {/* initialized with some values */};
|
||||||
T value;
|
T value;
|
||||||
for (const T item : vec) {
|
for (const T item : vec) {
|
||||||
@@ -12725,14 +12743,16 @@ Often, a loop that requires a `break` is a good candidate for a function (algori
|
|||||||
}
|
}
|
||||||
|
|
||||||
//BETTER: create a function and return inside loop
|
//BETTER: create a function and return inside loop
|
||||||
T search(const std::vector<T> &vec) {
|
T search(const std::vector<T> &vec)
|
||||||
|
{
|
||||||
for (const T &item : vec) {
|
for (const T &item : vec) {
|
||||||
if (/* some condition*/) return item;
|
if (/* some condition*/) return item;
|
||||||
}
|
}
|
||||||
return T(); //default value
|
return T(); //default value
|
||||||
}
|
}
|
||||||
|
|
||||||
void use2() {
|
void use2()
|
||||||
|
{
|
||||||
std::vector<T> vec = {/* initialized with some values */};
|
std::vector<T> vec = {/* initialized with some values */};
|
||||||
T value = search(vec);
|
T value = search(vec);
|
||||||
/* then do something with value */
|
/* then do something with value */
|
||||||
@@ -13251,20 +13271,23 @@ This also applies to `%`.
|
|||||||
|
|
||||||
##### Example, bad
|
##### Example, bad
|
||||||
|
|
||||||
double divide(int a, int b) {
|
double divide(int a, int b)
|
||||||
|
{
|
||||||
// BAD, should be checked (e.g., in a precondition)
|
// BAD, should be checked (e.g., in a precondition)
|
||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
##### Example, good
|
##### Example, good
|
||||||
|
|
||||||
double divide(int a, int b) {
|
double divide(int a, int b)
|
||||||
|
{
|
||||||
// good, address via precondition (and replace with contracts once C++ gets them)
|
// good, address via precondition (and replace with contracts once C++ gets them)
|
||||||
Expects(b != 0);
|
Expects(b != 0);
|
||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
double divide(int a, int b) {
|
double divide(int a, int b)
|
||||||
|
{
|
||||||
// good, address via check
|
// good, address via check
|
||||||
return b ? a / b : quiet_NaN<double>();
|
return b ? a / b : quiet_NaN<double>();
|
||||||
}
|
}
|
||||||
@@ -13500,8 +13523,7 @@ Simple code can be very fast. Optimizers sometimes do marvels with simple code
|
|||||||
|
|
||||||
vector<uint8_t> v(100000);
|
vector<uint8_t> v(100000);
|
||||||
|
|
||||||
for (size_t i = 0; i < v.size(); i += sizeof(uint64_t))
|
for (size_t i = 0; i < v.size(); i += sizeof(uint64_t)) {
|
||||||
{
|
|
||||||
uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
|
uint64_t& quad_word = *reinterpret_cast<uint64_t*>(&v[i]);
|
||||||
quad_word = ~quad_word;
|
quad_word = ~quad_word;
|
||||||
}
|
}
|
||||||
@@ -13637,7 +13659,7 @@ Don't let bad designs "bleed into" your code.
|
|||||||
|
|
||||||
Consider:
|
Consider:
|
||||||
|
|
||||||
template <class ForwardIterator, class T>
|
template<class ForwardIterator, class T>
|
||||||
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
|
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
|
||||||
|
|
||||||
`binary_search(begin(c), end(c), 7)` will tell you whether `7` is in `c` or not.
|
`binary_search(begin(c), end(c), 7)` will tell you whether `7` is in `c` or not.
|
||||||
@@ -13646,14 +13668,14 @@ However, it will not tell you where that `7` is or whether there are more than o
|
|||||||
Sometimes, just passing the minimal amount of information back (here, `true` or `false`) is sufficient, but a good interface passes
|
Sometimes, just passing the minimal amount of information back (here, `true` or `false`) is sufficient, but a good interface passes
|
||||||
needed information back to the caller. Therefore, the standard library also offers
|
needed information back to the caller. Therefore, the standard library also offers
|
||||||
|
|
||||||
template <class ForwardIterator, class T>
|
template<class ForwardIterator, class T>
|
||||||
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);
|
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);
|
||||||
|
|
||||||
`lower_bound` returns an iterator to the first match if any, otherwise to the first element greater than `val`, or `last` if no such element is found.
|
`lower_bound` returns an iterator to the first match if any, otherwise to the first element greater than `val`, or `last` if no such element is found.
|
||||||
|
|
||||||
However, `lower_bound` still doesn't return enough information for all uses, so the standard library also offers
|
However, `lower_bound` still doesn't return enough information for all uses, so the standard library also offers
|
||||||
|
|
||||||
template <class ForwardIterator, class T>
|
template<class ForwardIterator, class T>
|
||||||
pair<ForwardIterator, ForwardIterator>
|
pair<ForwardIterator, ForwardIterator>
|
||||||
equal_range(ForwardIterator first, ForwardIterator last, const T& val);
|
equal_range(ForwardIterator first, ForwardIterator last, const T& val);
|
||||||
|
|
||||||
@@ -13975,7 +13997,8 @@ For further information of how to use synchronization well to eliminate data rac
|
|||||||
There are many examples of data races that exist, some of which are running in
|
There are many examples of data races that exist, some of which are running in
|
||||||
production software at this very moment. One very simple example:
|
production software at this very moment. One very simple example:
|
||||||
|
|
||||||
int get_id() {
|
int get_id()
|
||||||
|
{
|
||||||
static int id = 1;
|
static int id = 1;
|
||||||
return id++;
|
return id++;
|
||||||
}
|
}
|
||||||
@@ -14000,9 +14023,9 @@ Local static variables are a common source of data races.
|
|||||||
int sz = read_vec(fs, buf, max); // read from fs into buf
|
int sz = read_vec(fs, buf, max); // read from fs into buf
|
||||||
gsl::span<double> s {buf};
|
gsl::span<double> s {buf};
|
||||||
// ...
|
// ...
|
||||||
auto h1 = async([&]{ sort(std::execution::par, s); }); // spawn a task to sort
|
auto h1 = async([&] { sort(std::execution::par, s); }); // spawn a task to sort
|
||||||
// ...
|
// ...
|
||||||
auto h2 = async([&]{ return find_all(buf, sz, pattern); }); // spawn a task to find matches
|
auto h2 = async([&] { return find_all(buf, sz, pattern); }); // spawn a task to find matches
|
||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14101,7 +14124,8 @@ Application concepts are easier to reason about.
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
void some_fun() {
|
void some_fun()
|
||||||
|
{
|
||||||
std::string msg, msg2;
|
std::string msg, msg2;
|
||||||
std::thread publisher([&] { msg = "Hello"; }); // bad: less expressive
|
std::thread publisher([&] { msg = "Hello"; }); // bad: less expressive
|
||||||
// and more error-prone
|
// and more error-prone
|
||||||
@@ -14793,7 +14817,7 @@ Here, if some other `thread` consumes `thread1`'s notification, `thread2` can wa
|
|||||||
void Sync_queue<T>::get(T& val)
|
void Sync_queue<T>::get(T& val)
|
||||||
{
|
{
|
||||||
unique_lock<mutex> lck(mtx);
|
unique_lock<mutex> lck(mtx);
|
||||||
cond.wait(lck, [this]{ return !q.empty(); }); // prevent spurious wakeup
|
cond.wait(lck, [this] { return !q.empty(); }); // prevent spurious wakeup
|
||||||
val = q.front();
|
val = q.front();
|
||||||
q.pop_front();
|
q.pop_front();
|
||||||
}
|
}
|
||||||
@@ -14974,14 +14998,12 @@ There is no explicit locking and both correct (value) return and error (exceptio
|
|||||||
|
|
||||||
void async_example()
|
void async_example()
|
||||||
{
|
{
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
auto v1 = std::async(std::launch::async, read_value, "v1.txt");
|
auto v1 = std::async(std::launch::async, read_value, "v1.txt");
|
||||||
auto v2 = std::async(std::launch::async, read_value, "v2.txt");
|
auto v2 = std::async(std::launch::async, read_value, "v2.txt");
|
||||||
std::cout << v1.get() + v2.get() << '\n';
|
std::cout << v1.get() + v2.get() << '\n';
|
||||||
}
|
}
|
||||||
catch (std::ios_base::failure & fail)
|
catch (std::ios_base::failure & fail) {
|
||||||
{
|
|
||||||
// handle exception here
|
// handle exception here
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15251,7 +15273,8 @@ Sometimes C++ code allocates the `volatile` memory and shares it with "elsewhere
|
|||||||
`volatile` local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral?
|
`volatile` local variables are nearly always wrong -- how can they be shared with other languages or hardware if they're ephemeral?
|
||||||
The same applies almost as strongly to member variables, for the same reason.
|
The same applies almost as strongly to member variables, for the same reason.
|
||||||
|
|
||||||
void f() {
|
void f()
|
||||||
|
{
|
||||||
volatile int i = 0; // bad, volatile local variable
|
volatile int i = 0; // bad, volatile local variable
|
||||||
// etc.
|
// etc.
|
||||||
}
|
}
|
||||||
@@ -15358,7 +15381,7 @@ Note that there is no return value that could contain an error code.
|
|||||||
The `File_handle` constructor might be defined like this:
|
The `File_handle` constructor might be defined like this:
|
||||||
|
|
||||||
File_handle::File_handle(const string& name, const string& mode)
|
File_handle::File_handle(const string& name, const string& mode)
|
||||||
:f{fopen(name.c_str(), mode.c_str())}
|
: f{fopen(name.c_str(), mode.c_str())}
|
||||||
{
|
{
|
||||||
if (!f)
|
if (!f)
|
||||||
throw runtime_error{"File_handle: could not open " + name + " as " + mode};
|
throw runtime_error{"File_handle: could not open " + name + " as " + mode};
|
||||||
@@ -15411,7 +15434,8 @@ C++ implementations tend to be optimized based on the assumption that exceptions
|
|||||||
try {
|
try {
|
||||||
for (gsl::index i = 0; i < vec.size(); ++i)
|
for (gsl::index i = 0; i < vec.size(); ++i)
|
||||||
if (vec[i] == x) throw i; // found x
|
if (vec[i] == x) throw i; // found x
|
||||||
} catch (int i) {
|
}
|
||||||
|
catch (int i) {
|
||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
return -1; // not found
|
return -1; // not found
|
||||||
@@ -16292,7 +16316,7 @@ Flag every exception specification.
|
|||||||
catch (Base& b) { /* ... */ }
|
catch (Base& b) { /* ... */ }
|
||||||
catch (Derived& d) { /* ... */ }
|
catch (Derived& d) { /* ... */ }
|
||||||
catch (...) { /* ... */ }
|
catch (...) { /* ... */ }
|
||||||
catch (std::exception& e){ /* ... */ }
|
catch (std::exception& e) { /* ... */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
If `Derived`is derived from `Base` the `Derived`-handler will never be invoked.
|
If `Derived`is derived from `Base` the `Derived`-handler will never be invoked.
|
||||||
@@ -16359,7 +16383,8 @@ This gives a more precise statement of design intent, better readability, more e
|
|||||||
// ...
|
// ...
|
||||||
};
|
};
|
||||||
|
|
||||||
void f(const Point& pt) {
|
void f(const Point& pt)
|
||||||
|
{
|
||||||
int x = pt.getx(); // ERROR, doesn't compile because getx was not marked const
|
int x = pt.getx(); // ERROR, doesn't compile because getx was not marked const
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17665,7 +17690,7 @@ Because that's the best we can do without direct concept support.
|
|||||||
|
|
||||||
##### Example
|
##### Example
|
||||||
|
|
||||||
template <typename T>
|
template<typename T>
|
||||||
enable_if_t<is_integral_v<T>>
|
enable_if_t<is_integral_v<T>>
|
||||||
f(T v)
|
f(T v)
|
||||||
{
|
{
|
||||||
@@ -17673,7 +17698,7 @@ Because that's the best we can do without direct concept support.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Equivalent to:
|
// Equivalent to:
|
||||||
template <Integral T>
|
template<Integral T>
|
||||||
void f(T v)
|
void f(T v)
|
||||||
{
|
{
|
||||||
// ...
|
// ...
|
||||||
@@ -17731,7 +17756,8 @@ Eases tool creation.
|
|||||||
}
|
}
|
||||||
|
|
||||||
template<typename Iter>
|
template<typename Iter>
|
||||||
Iter algo(Iter first, Iter last) {
|
Iter algo(Iter first, Iter last)
|
||||||
|
{
|
||||||
for (; first != last; ++first) {
|
for (; first != last; ++first) {
|
||||||
auto x = sqrt(*first); // potentially surprising dependency: which sqrt()?
|
auto x = sqrt(*first); // potentially surprising dependency: which sqrt()?
|
||||||
helper(first, x); // potentially surprising dependency:
|
helper(first, x); // potentially surprising dependency:
|
||||||
@@ -19017,7 +19043,8 @@ Doing so takes away an `#include`r's ability to effectively disambiguate and to
|
|||||||
|
|
||||||
bool copy(/*... some parameters ...*/); // some function that happens to be named copy
|
bool copy(/*... some parameters ...*/); // some function that happens to be named copy
|
||||||
|
|
||||||
int main() {
|
int main()
|
||||||
|
{
|
||||||
copy(/*...*/); // now overloads local ::copy and std::copy, could be ambiguous
|
copy(/*...*/); // now overloads local ::copy and std::copy, could be ambiguous
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21061,7 +21088,7 @@ Some styles distinguish members from local variable, and/or from global variable
|
|||||||
|
|
||||||
struct S {
|
struct S {
|
||||||
int m_;
|
int m_;
|
||||||
S(int m) :m_{abs(m)} { }
|
S(int m) : m_{abs(m)} { }
|
||||||
};
|
};
|
||||||
|
|
||||||
This is not harmful and does not fall under this guideline because it does not encode type information.
|
This is not harmful and does not fall under this guideline because it does not encode type information.
|
||||||
@@ -21722,7 +21749,8 @@ Here is an example of the last option:
|
|||||||
|
|
||||||
class B {
|
class B {
|
||||||
public:
|
public:
|
||||||
B() {
|
B()
|
||||||
|
{
|
||||||
/* ... */
|
/* ... */
|
||||||
f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
|
f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
|
||||||
/* ... */
|
/* ... */
|
||||||
@@ -21935,7 +21963,8 @@ Consider the following advice and requirements found in the C++ Standard:
|
|||||||
Deallocation functions, including specifically overloaded `operator delete` and `operator delete[]`, fall into the same category, because they too are used during cleanup in general, and during exception handling in particular, to back out of partial work that needs to be undone.
|
Deallocation functions, including specifically overloaded `operator delete` and `operator delete[]`, fall into the same category, because they too are used during cleanup in general, and during exception handling in particular, to back out of partial work that needs to be undone.
|
||||||
Besides destructors and deallocation functions, common error-safety techniques rely also on `swap` operations never failing -- in this case, not because they are used to implement a guaranteed rollback, but because they are used to implement a guaranteed commit. For example, here is an idiomatic implementation of `operator=` for a type `T` that performs copy construction followed by a call to a no-fail `swap`:
|
Besides destructors and deallocation functions, common error-safety techniques rely also on `swap` operations never failing -- in this case, not because they are used to implement a guaranteed rollback, but because they are used to implement a guaranteed commit. For example, here is an idiomatic implementation of `operator=` for a type `T` that performs copy construction followed by a call to a no-fail `swap`:
|
||||||
|
|
||||||
T& T::operator=(const T& other) {
|
T& T::operator=(const T& other)
|
||||||
|
{
|
||||||
auto temp = other;
|
auto temp = other;
|
||||||
swap(temp);
|
swap(temp);
|
||||||
return *this;
|
return *this;
|
||||||
|
|||||||
Reference in New Issue
Block a user