本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
1From C to C++: Classes and Resource Management
The weather station of Brenmoor writes its readings to log files whose first line says LOG v2. A C function that checks this header opens the file, reads one line and gives up early when the line is wrong. The program below calls it once on a good log and ten times on a bad one, and before and after it counts the files the system holds open for the program (open_files, not shown, asks the system about each file number from 0 to 255; Chapter 14 explains these numbers).
// The version number of a log whose first line is "LOG v<n> ...", or -1.
int header_version(const char *path)
{
FILE *f = fopen(path, "r");
if (f == NULL)
return -1;
char line[128];
if (fgets(line, sizeof line, f) == NULL)
return -1; // leaves f open
if (strncmp(line, "LOG v", 5) != 0)
return -1; // leaves f open
int version = line[5] - '0';
fclose(f);
return version;
}
{
printf("open files at start: %d\n", open_files());
printf("good.log: version %d\n", header_version("good.log"));
for (int i = 0; i < 10; i++)
header_version("bad.log");
printf("bad.log read 10 times: version -1 each time\n");
printf("open files at end: %d\n", open_files());
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o early_return early_return.c -lm && ./early_return
open files at start: 3
good.log: version 2
bad.log read 10 times: version -1 each time
open files at end: 13
The three files open at the start are the standard input, output and error. Each call on the bad log returned through one of the two early returns, and neither of them calls fclose: ten calls left ten files open. A long-running server that did this a few thousand times would be refused its next fopen. The bug is not in a hard line; it is in a missing one, on a path the author did not think about. This chapter moves to C++, whose objects release what they hold when they die, on every path out of a function, including the paths an error takes.
You already know
In C, a variable declared in a block is automatic: it lives from its declaration to the end of the block, in the frame of the running function, and disappears when the function returns. Memory taken with malloc lives until free; a block nobody frees any more is a leak, and freeing a block twice is undefined behaviour. Who frees what is a convention written in comments, which the compiler cannot check. A class (the school volumes, in Python) groups data and the methods that use them, and its constructor builds each new instance.
1.1 C++ as a better C
C++ grew out of C, and most C programs are also C++ programs. Its compiler here is g++, used with the standard of 2020 (-std=c++20). This part of the book uses what C++ adds to C to write the same kind of systems code more safely; the next four chapters go on to copies and moves, polymorphism, templates and the standard library.
History — C with Classes
Bjarne Stroustrup began the work that became C++ in 1979, under the name “C with Classes”: he wanted to write efficient systems programs in the style of the Simula language, with its classes. The first version called C++ was used inside AT&T in August 1983, and the name C++ (C, incremented) appeared late that year. The language has been an ISO standard since 1998; the edition used in this book, C++20, was published in December 2020.
Definition 1.1 (Reference)
A reference of type T & is another name for an existing object of type T. It is bound once, when it is declared, and never rebound; reading or assigning the reference reads or assigns the object it names. A reference cannot be null. A const reference const T & names the object but allows only reading it.
A reference does what a pointer does in C, without the * and & at every use and without the null case. Passed as a parameter, T & lets the function change the caller’s variable, and const T & lets it read a large object without copying it.
Definition 1.2 (Namespace)
A namespace is a named region of declarations. A name n declared in the namespace ns is written ns::n outside it, so that two libraries may both declare an area without a clash. The standard library declares everything in the namespace std.
C++ also allows overloading: two functions may share a name if their parameter lists differ, and the compiler picks the one whose parameters match the arguments of each call. The library types std::string (a string that owns its characters and grows as needed) and std::vector<T> (an array of T that grows as needed) are used in this chapter as black boxes; Chapter 5 opens them. Output goes through std::cout <<, which is overloaded for every type it can print.
namespace geometry {
double area(double side) { return side * side; } // a square
double area(double w, double h) { return w * h; } // a rectangle
}
void swap_ints(int &a, int &b) // a and b are other names for the caller's ints
{
int t = a;
a = b;
b = t;
}
int total_length(const std::vector<std::string> &words) // read-only, not copied
{
int n = 0;
for (const std::string &w : words)
n += static_cast<int>(w.size());
return n;
}
int main()
{
int x = 1, y = 2;
int &r = x; // r is x, from now on
r = 10;
swap_ints(x, y);
std::cout << "x = " << x << ", y = " << y << '\n';
std::cout << geometry::area(3.0) << ' ' << geometry::area(2.0, 4.5) << '\n';
std::vector<std::string> streets{"Mill Lane", "Harbour Road", "Station Street"};
streets.push_back("Elm Row");
std::cout << streets.size() << " streets, " << total_length(streets) << " letters\n";
return 0;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o references references.cpp && ./references
x = 2, y = 10
9 9
4 streets, 42 letters
Example 1.3 (Following the references)
The line int &r = x; makes r a second name of x, so r = 10 sets x to 10. In swap_ints(x, y), the parameters a and b are bound to x and y themselves: the function exchanges the caller’s values and main prints x = 2, y = 10. The two area calls go to two different functions, and , both 9. In total_length, the parameter const std::vector<std::string> &words reads the caller’s vector without copying its four strings, whose lengths make 42.
A const reference promises that the function will not change the object. The promise is checked by the compiler, so breaking it is an error, not a run-time surprise.
void add_bonus(const int &score)
{
score += 10; // the compiler refuses
std::cout << score << '\n';
}
int main()
{
int s = 75;
add_bonus(s);
return 0;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o const_error const_error.cpp && ./const_error
const_error.cpp: In function 'void add_bonus(const int&)':
const_error.cpp:6:11: error: assignment of read-only reference 'score'
6 | score += 10; // the compiler refuses
| ~~~~~~^~~~~
[exit status 1]
1.2 Classes
A C structure groups data, and any function may change its fields. A C++ class groups data and the functions allowed to touch them, and decides who may call what.
Definition 1.4 (Class, object, member)
A class is a type declared with class or struct that groups data members (its fields) and member functions (functions declared inside it). An object of a class is a region of memory holding one value of each data member; a member function is called on an object, obj.f(args), and inside it the names of the members refer to that object’s members (the object itself is *this).
Definition 1.5 (Access specifier)
The access specifiers public: and private: divide a class’s declarations into those any code may use and those only the class’s own member functions may use. A class starts private, a struct public, for its members and for its base classes (Chapter 3); otherwise the two keywords are the same.
Definition 1.6 (Constructor, destructor)
A constructor of a class C is a member function named C, without a return type, that the compiler calls each time an object of C is created; its member initialiser list (after the :) gives each data member its first value. The destructor ~C() is the member function the compiler calls when the object’s lifetime ends; a class has exactly one.
The constructor is the only way in: there is no object of C that a constructor did not finish building. That is what makes the following definition useful.
Definition 1.7 (Class invariant)
A class invariant is a property of the data members that every constructor establishes and every public member function preserves. A constructor that cannot establish it does not return: it reports the failure (Section 1.4), and no object exists.
If the data members are private, only the class’s own functions can break the invariant, so checking it is a matter of reading one class, not the whole program. The class below keeps a fraction in lowest terms with a positive denominator, so that two equal fractions have equal members.
class Fraction {
public:
// Invariant: den_ > 0 and gcd(num_, den_) == 1.
Fraction(long num, long den) : num_(num), den_(den)
{
if (den_ == 0)
throw std::invalid_argument("zero denominator");
if (den_ < 0) {
num_ = -num_;
den_ = -den_;
}
long g = std::gcd(num_, den_);
num_ /= g;
den_ /= g;
}
Fraction(long whole) : Fraction(whole, 1) {}
long num() const { return num_; }
long den() const { return den_; }
Fraction operator+(const Fraction &o) const
{
return Fraction(num_ * o.den_ + o.num_ * den_, den_ * o.den_);
}
Fraction operator*(const Fraction &o) const
{
return Fraction(num_ * o.num_, den_ * o.den_);
}
bool operator==(const Fraction &o) const = default;
private:
long num_;
long den_;
};
int main()
{
Fraction a(6, -8);
Fraction b(1, 4);
std::cout << "a = " << a << ", b = " << b << '\n';
std::cout << "a + b = " << a + b << ", a * b = " << a * b << '\n';
std::cout << "a + 1 = " << a + 1 << '\n';
std::cout << std::boolalpha << "2/4 == 1/2: "
<< (Fraction(2, 4) == Fraction(1, 2)) << '\n';
try {
Fraction bad(3, 0);
std::cout << "never printed " << bad << '\n';
} catch (const std::invalid_argument &e) {
std::cout << "refused: " << e.what() << '\n';
}
return 0;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o fraction_demo fraction_demo.cpp && ./fraction_demo
a = -3/4, b = 1/4
a + b = -1/2, a * b = -3/16
a + 1 = 1/4
2/4 == 1/2: true
refused: zero denominator
Example 1.8 (Building )
The initialiser list sets num_ = 6, den_ = -8. The body finds den_ nonzero and negative, so it negates both, , then divides both by (std::gcd returns a non-negative result): . The sum a + b is built by the constructor too, from over , and comes out as . The expression a + 1 works because Fraction(long whole) is a constructor with one argument: the compiler uses it to convert 1 into . The defaulted operator== compares the members one by one, which is correct only because the invariant makes the representation unique.
Definition 1.9 (Const member function, const-correctness)
A member function declared with const after its parameter list is a const member function: it may not change the object’s data members, and it is the only kind of member function that can be called on a const object or through a const reference. A program is const-correct when every function that does not change an object takes it as const, and every member function that does not change its object is const.
In Listing 1.4, num(), den(), operator+ and operator* are const: they read *this and build a new fraction. A function that takes a const Fraction & can call them and nothing else. Const-correctness spreads: once operator<< takes its fraction by const reference, the accessors it calls must be const.
1.3 Resource acquisition is initialisation
An automatic object of a class lives from its declaration to the end of its block, as a C variable does; the difference is that the compiler calls its destructor at that end. The class Noisy prints a line in its constructor and one in its destructor, so that a run shows every lifetime.
class Noisy {
public:
explicit Noisy(std::string name) : name_(std::move(name))
{
std::cout << " make " << name_ << '\n';
}
~Noisy() { std::cout << " drop " << name_ << '\n'; }
Noisy(const Noisy &) = delete;
Noisy &operator=(const Noisy &) = delete;
private:
std::string name_;
};
void visit()
{
Noisy c("c (in visit)");
std::cout << " visit returns\n";
}
int main()
{
std::cout << "main starts\n";
Noisy a("a");
{
Noisy b1("b1");
Noisy b2("b2");
visit();
std::cout << " inner scope ends\n";
}
for (int i = 0; i < 2; i++) {
Noisy d("d" + std::to_string(i));
}
std::cout << "main returns\n";
return 0;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o lifetimes lifetimes.cpp && ./lifetimes
main starts
make a
make b1
make b2
make c (in visit)
visit returns
drop c (in visit)
inner scope ends
drop b2
drop b1
make d0
drop d0
make d1
drop d1
main returns
drop a
The language fixes the order: when a block ends, its automatic objects are destroyed in the reverse order of their construction, and an object’s members are destroyed after its destructor’s body, in the reverse order of their declaration.
Objects declared outside every function (global objects) are built before main starts and destroyed after it returns, also in reverse order.
Proposition 1.10 (Lifetimes nest)
Let and be automatic objects of one thread, with constructed before and both alive at some moment. Then is destroyed before . In other words, the lifetimes of automatic objects are nested intervals: two of them are either disjoint or one contains the other.
Proof. Let and be the blocks that declare and . Blocks are entered and left in a nested way: a block is left only after every block entered inside it has been left (this is how a function’s calls and its braces work). At the moment is constructed, is alive, so is still active. Either : then was declared after in the same block, and the block destroys them in reverse order, first. Or : then was entered after and while was active, so is left first, and dies when is left, while waits for . In both cases dies first. ∎
The output above is this proposition at work: c is born and dies inside visit, b2 dies before b1, and a, born first, dies last. The drawing below puts each lifetime on a time axis.
d0 and d1, born in two iterations of the loop) or nested (c inside b2 inside b1 inside a).A destructor that runs at a known moment, on every way out of a block, is exactly what the header check of the opening lacked. The idea gets a name.
Definition 1.11 (Resource, RAII)
A resource is anything a program acquires and must give back: a block of heap memory, an open file, a lock, a network connection. Resource acquisition is initialisation (RAII) is the rule that every resource is acquired by the constructor of an object that owns it, and released by that object’s destructor.
Method 1.12 (Owning a resource with an object)
To make a resource safe:
- write a class whose constructor acquires the resource and fails (throws, Section 1.4) if it cannot, so that every object of the class holds a resource;
- release the resource in the destructor, and nowhere else;
- forbid copying (
= delete), so that one resource has one owner (Chapter 2 shows how ownership can move instead); - give the class the operations the program needs, and use it as an automatic object or a data member, never with a raw
fopen,mallocornewin the code that uses it.
class File {
public:
File(const std::string &path, const char *mode) : f_(std::fopen(path.c_str(), mode))
{
if (f_ == nullptr)
throw std::runtime_error("cannot open " + path);
}
~File() { std::fclose(f_); }
File(const File &) = delete; // one owner: no copies
File &operator=(const File &) = delete;
std::optional<std::string> read_line() // without its newline; nothing at the end
{
std::string line;
int c;
while ((c = std::fgetc(f_)) != EOF && c != '\n')
line += static_cast<char>(c);
if (c == EOF && line.empty())
return std::nullopt;
return line;
}
void write(const std::string &s)
{
if (std::fputs(s.c_str(), f_) == EOF)
throw std::runtime_error("write failed");
}
void flush() // a full disk shows up here, not in write
{
if (std::fflush(f_) == EOF)
throw std::runtime_error("flush failed");
}
private:
std::FILE *f_;
};
The class follows the four steps: the constructor opens or throws, the destructor closes, the two lines with = delete remove the copy operations, and read_line, write and flush are the operations. std::optional<std::string> holds either a string or nothing, which is how read_line says “end of file” without a special string. Here is the header check again, with the file owned by a File.
int header_version(const std::string &path)
{
File f(path, "r"); // throws if the file cannot be opened
std::optional<std::string> line = f.read_line();
if (!line || line->rfind("LOG v", 0) != 0)
return -1; // f is closed here
return (*line)[5] - '0'; // and here
}
main is the C version’s, plus a missing file code/bachelor-2/01-cpp-classes-raii/listings/file_demo.cpp$ g++ -std=c++20 -O2 -Wall -Wextra -o file_demo file_demo.cpp && ./file_demo
open files at start: 3
good.log: version 2
bad.log read 10 times: version -1 each time
open files at end: 3
missing.log: cannot open missing.log
The function has the same two exits as the C version, but neither calls fclose: leaving the function ends f’s lifetime, and the destructor closes the file on whichever path is taken. A missing file is no longer a return value to check: the constructor throws, main catches, and no File without a file ever exists. The drawing shows what f is in memory.
File is one pointer in the frame of the function that declares it. The FILE it points to lives on the heap and refers to a file the operating system keeps open. When the frame is popped, the destructor releases both; the opening’s C code popped the frame and kept them.Proposition 1.13 (Release on every path)
In a function whose resources are all owned by automatic RAII objects (or by members of such objects), each resource that was acquired is released exactly once, whatever path the function leaves by: a return, the end of the body, or an exception (Section 1.4).
Proof. By induction on the depth of nesting of the blocks. Consider a block whose inner blocks satisfy the claim, and a resource it acquires directly: by the method, the acquisition is the construction of an object declared in the block. If the constructor fails, never existed and nothing was acquired, so nothing must be released. If it succeeds, is alive until the block is left; every way of leaving it (falling off its end, return, break, continue, goto out of it, an exception crossing it) ends ’s lifetime, and the compiler then calls the destructor once, which releases the resource once. Copies are deleted, so no second object releases it. Resources acquired in inner blocks are released by the induction hypothesis, before the block is left, and resources held by members of are released when ’s members are destroyed. The outermost block is the function body, which gives the claim. ∎
1.4 Exceptions
A constructor has no return value through which to report a failure, and a deep chain of calls makes a return code travel through every level, each of which must remember to check it. C++ reports errors with exceptions.
Definition 1.14 (Exception, throw, handler)
An exception is an object that reports an error. A throw expression throw e; stops the current function and starts the search for a handler. A try block is followed by one or more handlers catch (const T &x) {body}: the first handler, in order, whose type T is the type of the exception or one of its base classes catches it. catch (...) catches anything, and throw; inside a handler throws the same exception again. If no handler catches it, the program ends.
The library’s exceptions are classes derived from std::exception, whose member what() returns the message. Two families matter here: std::logic_error, with std::invalid_argument, std::domain_error, std::length_error and std::out_of_range, for errors a program could have avoided; and std::runtime_error, for errors only a run can reveal, such as a missing file.
A handler for const std::logic_error & therefore also catches an std::out_of_range; Chapter 3 explains derived classes.
Definition 1.15 (Stack unwinding)
Between a throw and the handler that catches it, the program leaves every block and every function in between. Stack unwinding is this departure: each frame left is popped, and each automatic object of each block left is destroyed, in the reverse order of construction, as if its block had ended.
void parse(int depth)
{
Noisy n("p" + std::to_string(depth));
if (depth == 3)
throw std::runtime_error("bad record at depth 3");
parse(depth + 1);
std::cout << " never printed\n";
}
int main()
{
Noisy m("m");
try {
Noisy t("t");
parse(1);
} catch (const std::runtime_error &e) {
std::cout << "caught: " << e.what() << '\n';
}
std::cout << "main goes on\n";
return 0;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o unwind unwind.cpp && ./unwind
make m
make t
make p1
make p2
make p3
drop p3
drop p2
drop p1
drop t
caught: bad record at depth 3
main goes on
drop m
Neither never printed line appeared: parse(3) threw, parse(2) and parse(1) were left in the middle of their bodies, and on the way each frame destroyed its Noisy. The t of the try block went too, since the block was left; m, declared outside the try, survived until main returned. Proposition 1.13 is why this matters: an exception is one more way out of a block, and the destructors take it as well.
parse(3) throws, the newest on top. Unwinding pops frames downward to the frame whose try block has a matching handler, destroying each object it passes, then runs the handler.An exception may interrupt an operation half way. What the operation promises about that case is part of its specification, in one of three standard forms.
Definition 1.16 (Exception-safety guarantees)
An operation gives the basic guarantee if, when it throws, no resource is leaked and every object it touched still satisfies its invariant, though its value may have changed. It gives the strong guarantee if, when it throws, the state is exactly as before the call (“commit or roll back”). It gives the no-throw guarantee if it never throws; a function declares it with noexcept.
If an exception tries to leave a noexcept function, the program is ended by std::terminate; destructors are noexcept unless declared otherwise, which is why a destructor must never let an exception out.
The two member functions below add a batch of names to a roster that holds Ada and Brendan, and fail on an empty name. The program (its main is not shown) gives both versions the batch Cora, Dev, the empty name, Emil, and prints the size of each roster after the failure.
class Roster {
public:
// Basic guarantee: on failure the roster is valid, but may hold some new names.
void add_all_basic(const std::vector<std::string> &names)
{
for (const std::string &n : names)
names_.push_back(checked(n));
}
// Strong guarantee: on failure the roster is exactly as before.
void add_all_strong(const std::vector<std::string> &names)
{
std::vector<std::string> copy = names_;
for (const std::string &n : names)
copy.push_back(checked(n));
names_.swap(copy); // cannot throw
}
std::size_t size() const { return names_.size(); }
private:
static const std::string &checked(const std::string &n)
{
if (n.empty())
throw std::invalid_argument("empty name");
return n;
}
std::vector<std::string> names_{"Ada", "Brendan"};
};
$ g++ -std=c++20 -O2 -Wall -Wextra -o guarantee guarantee.cpp && ./guarantee
basic: empty name, size now 4
strong: empty name, size now 2
Both versions leak nothing (the vectors and strings own their memory) and leave a valid roster, so both give the basic guarantee. The second also gives the strong one: it works on a copy, and the only operation on the real roster, swap, exchanges two vectors’ internal pointers and cannot throw. The pattern is general: do the work that may fail on the side, then commit with operations that cannot fail. Its price is the copy.
Cora and Dev added; the strong guarantee leaves the state of before.A thrown exception is not free. The program below times a million calls of a function that fails, once reporting the failure by a return value and once by a throw caught one call up, and the same calls when nothing fails.
__attribute__((noinline)) int check_code(int x) { return x < 0 ? -1 : x; }
__attribute__((noinline)) int check_throw(int x)
{
if (x < 0)
throw std::domain_error("negative");
return x;
}
double ok_code = ns_per_call([&](int i) { sink = sink + check_code(i); }, n);
double ok_throw = ns_per_call([&](int i) { sink = sink + check_throw(i); }, n);
double bad_code = ns_per_call([&](int i) {
if (check_code(-i - 1) < 0) sink = sink + 1; }, n);
double bad_throw = ns_per_call([&](int i) {
try { sink = sink + check_throw(-i - 1); } catch (const std::domain_error &) { sink = sink + 1; }
}, n);
ns_per_call times a million calls of its argument) code/bachelor-2/01-cpp-classes-raii/listings/exception_cost.cpp$ g++ -std=c++20 -O2 -Wall -Wextra -o exception_cost exception_cost.cpp && ./exception_cost
success, return code: 0.54 ns per call
success, may throw: 0.477 ns per call
failure, return code: 0.582 ns per call
failure, throw/catch: 786 ns per call
a throw costs about 1352 failed return codes
The success path costs the same whether the function may throw or not: with this compiler, the code that handles an exception is kept apart from the normal path and runs only when something is thrown. A throw, on the other hand, costs hundreds of nanoseconds: the exception object is allocated, the frames are searched for a handler, and the stack is unwound. Exceptions are therefore meant for the exceptional, not for an outcome that occurs on every other call.
In practice — Errors: exceptions or values
Throw when a failure is rare and the code that can handle it is far from the code that detects it: a constructor that cannot establish its invariant, a missing configuration file, a full disk. Return a value (a boolean, an std::optional, an error code) when the failure is a normal outcome that the immediate caller decides on, such as a search that finds nothing or a parse of user input that fails often. In both cases, own every resource with an object, so that either way out is safe.
1.5 Exercises
Exercise 1.1 ★
Predict every line printed by the program below (Noisy is Listing 1.6).
Noisy g("global");
void f(int k)
{
Noisy x("x" + std::to_string(k));
if (k > 0)
f(k - 1);
}
int main()
{
Noisy a("a");
f(1);
{
Noisy b("b");
}
return 0;
}
Solution
Solution of Exercise 1.1.
The global object is built before main and destroyed after it; inside, f(1) makes x1, calls f(0), which makes and drops x0, then drops x1; the inner block makes and drops b:
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_order exo_order.cpp && ./exo_order
make global
make a
make x1
make x0
drop x0
drop x1
make b
drop b
drop a
drop global
Exercise 1.2 ★
The function longer should return the longer of two names. The compiler warns, and the run prints nothing at all, not even a newline. Explain the warning, why the program’s behaviour is undefined, and fix the function in the simplest way.
const std::string &longer(const std::string &a, const std::string &b)
{
std::string result = a.size() >= b.size() ? a : b;
return result;
}
int main()
{
std::string x = "Harbour Road", y = "Elm Row";
std::cout << longer(x, y) << '\n';
return 0;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_dangling exo_dangling.cpp && ./exo_dangling
exo_dangling.cpp: In function 'const string& longer(const string&, const string&)':
exo_dangling.cpp:8:12: warning: reference to local variable 'result' returned [-Wreturn-local-addr]
8 | return result;
| ^~~~~~
exo_dangling.cpp:7:17: note: declared here
7 | std::string result = a.size() >= b.size() ? a : b;
| ^~~~~~
[exit status -11]
Solution
Solution of Exercise 1.2.
result is an automatic object of longer: it dies when longer returns, so the returned reference names an object that no longer exists (a dangling reference), and reading it in main is undefined behaviour. Any outcome is allowed; this compiler, knowing the reference is dangling, returned a null address and the print produced nothing. The simplest fix returns a copy: declare the return type std::string instead of const std::string &, and the body can shrink to return a.size() >= b.size() ? a : b;. (Returning a or b by reference would also be correct, since they name the caller’s objects, but only as long as those outlive the use.)
Exercise 1.3 ★
Write a class IntArray that owns a heap array of n ints, zero-filled, given to its constructor: size(), at(i) returning a reference (with a const version for const arrays), throwing std::out_of_range when , and no copies. Which step of Method 1.12 does each part of your class implement?
Solution
Solution of Exercise 1.3.
class IntArray {
public:
explicit IntArray(std::size_t n) : n_(n), data_(new int[n]{}) {} // zero-filled
~IntArray() { delete[] data_; }
IntArray(const IntArray &) = delete;
IntArray &operator=(const IntArray &) = delete;
std::size_t size() const { return n_; }
int &at(std::size_t i) { return data_[check(i)]; }
const int &at(std::size_t i) const { return data_[check(i)]; }
private:
std::size_t check(std::size_t i) const
{
if (i >= n_)
throw std::out_of_range("IntArray index " + std::to_string(i));
return i;
}
std::size_t n_;
int *data_;
};
IntArray code/bachelor-2/01-cpp-classes-raii/exercises/int_array.hppStep 1: the constructor acquires the block (new int[n]{} zero-fills it, and throws std::bad_alloc if there is no memory, so no object without a block exists). Step 2: the destructor’s delete[] is the only release. Step 3: the two deleted functions. Step 4: size and the two at, which keep every access inside the block. Tested in tests/exercises_test.cpp.
Exercise 1.4 ★
A function contains nested blocks, and block (for , from the outermost) declares Noisy objects named j.1, …, j.m before it opens block . How many lines does a call print? Give the first three and the last three drop lines, and prove your answer with Proposition 1.10.
Solution
Solution of Exercise 1.4.
Each of the objects prints one make and one drop line: lines. When n.m is made, all objects are alive (the blocks are nested and none has ended), so by Proposition 1.10 they die in the reverse order of construction. Construction order is 1.1, …, 1.m, 2.1, …, n.m, so the first drops are n.m, n.(m-1), n.(m-2) and the last three 1.3, 1.2, 1.1 (for ).
Exercise 1.5 ★★
Predict the output of the program below, which throws a different exception for each through three levels of handlers. Name, for each , the handler that catches and the rule that decides it.
void step(int k)
{
try {
if (k == 1) throw std::invalid_argument("one");
if (k == 2) throw std::out_of_range("two");
if (k == 3) throw std::runtime_error("three");
if (k == 4) throw 4;
} catch (const std::out_of_range &e) {
std::cout << k << ": inner out_of_range " << e.what() << '\n';
} catch (const std::invalid_argument &e) {
std::cout << k << ": inner invalid_argument " << e.what() << '\n';
throw;
}
std::cout << k << ": step done\n";
}
int main()
{
for (int k = 0; k <= 4; k++) {
try {
try {
step(k);
} catch (const std::logic_error &e) {
std::cout << k << ": middle logic_error " << e.what() << '\n';
}
} catch (const std::exception &e) {
std::cout << k << ": outer exception " << e.what() << '\n';
} catch (...) {
std::cout << k << ": outer catch-all\n";
}
}
return 0;
}
Solution
Solution of Exercise 1.5.
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_handlers exo_handlers.cpp && ./exo_handlers
0: step done
1: inner invalid_argument one
1: middle logic_error one
2: inner out_of_range two
2: step done
3: outer exception three
4: outer catch-all
: nothing thrown. : invalid_argument skips the out_of_range handler (not its type) and is caught by the second inner handler, which prints and rethrows with throw;; the middle handler catches it, since invalid_argument derives from logic_error, and step done is never reached. : the first inner handler matches; the exception is finished, so step goes on and prints step done. : runtime_error matches neither inner handler nor logic_error; the outer std::exception handler catches it. : an int is not a class derived from std::exception; only catch (...) matches.
Exercise 1.6 ★★
The class Merger opens two files in its constructor and closes them in its destructor. Explain the output, then fix the class with Method 1.12, without writing a destructor.
class Merger {
public:
Merger(const char *first, const char *second)
: a_(std::fopen(first, "r")), b_(std::fopen(second, "r"))
{
if (a_ == nullptr || b_ == nullptr)
throw std::runtime_error("cannot open both files");
}
~Merger()
{
std::fclose(a_);
std::fclose(b_);
}
private:
std::FILE *a_;
std::FILE *b_;
};
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_two_files exo_two_files.cpp && ./exo_two_files
cannot open both files; open files: 4
cannot open both files; open files: 5
cannot open both files; open files: 6
cannot open both files; open files: 7
cannot open both files; open files: 8
Solution
Solution of Exercise 1.6.
Each time, the first fopen succeeds, the second fails, and the constructor throws. A constructor that throws never produces an object, so the destructor never runs, and the raw pointer a_ has no destructor of its own: one file leaks per failure, 4, 5, …, 8 open files. The fix makes each file a member that owns itself:
class Merger {
public:
Merger(const char *first, const char *second) : a_(first, "r"), b_(second, "r") {}
// No destructor to write: a_ and b_ close themselves. If b_'s constructor throws,
// the fully built member a_ is destroyed before the exception leaves.
private:
File a_;
File b_;
};
Merger with File members code/bachelor-2/01-cpp-classes-raii/exercises/merger.hppWhen b_’s constructor throws, the members already built (here a_) are destroyed before the exception leaves the constructor, so a_ closes its file. The test opens and fails ten times and finds the count of open files unchanged.
Exercise 1.7 ★★
Write a class template ScopeGuard<F> whose constructor takes a callable action and whose destructor calls it when the guard’s scope ends, unless dismiss() was called first. The guard cannot be copied. Show how it gives a C-style function (two mallocs, an fopen) one cleanup on every path, and why dismiss is needed when the function succeeds and hands the resources to its caller. (Write ScopeGuard g([&] {free(p);});: C++17 deduces F.)
Solution
Solution of Exercise 1.7.
template <class F> class ScopeGuard {
public:
explicit ScopeGuard(F action) : action_(std::move(action)) {}
~ScopeGuard()
{
if (active_)
action_();
}
void dismiss() noexcept { active_ = false; }
ScopeGuard(const ScopeGuard &) = delete;
ScopeGuard &operator=(const ScopeGuard &) = delete;
private:
F action_;
bool active_ = true;
};
ScopeGuard code/bachelor-2/01-cpp-classes-raii/exercises/scope_guard.hppIn a C-style function, right after each acquisition succeeds, declare its guard: char *a = (char *)malloc(n); if (!a) return -1; ScopeGuard ga([&] {free(a);});, then the same for the second block and for the file. Every later return (or exception) runs the guards declared so far, newest first, so each path frees exactly what was acquired. When the function succeeds and returns the resources to its caller, they must not be freed: the function calls dismiss() on each guard just before the final return.
Exercise 1.8 ★★
A function acquires resources, in order, and contains checks, check coming after the first acquisitions (), each of which returns early. Show that it has exit paths by return. Written in C, how many release calls must its author write so that nothing leaks? Written with one RAII object per resource, how many, and why does Proposition 1.13 make this count right?
Solution
Solution of Exercise 1.8.
Each of the checks has its return, and the end of the body is one more: paths. In C, path must release the resources held at check , and the last path all : the author writes release calls. With one RAII object per resource, the function contains none: the release is written once, in each class’s destructor. By Proposition 1.13, on path exactly the objects built so far are destroyed, each once, which is exactly the set the C author had to release by hand.
Exercise 1.9 ★★
Write BoundedStack<T, N>, a stack of at most elements of type T with push, pop, top and size. push on a full stack throws std::length_error; push must give the strong guarantee even when copying a T throws. Explain why your implementation does.
Solution
Solution of Exercise 1.9.
template <class T, std::size_t N> class BoundedStack {
public:
BoundedStack() { items_.reserve(N); } // after this, push_back never reallocates
// Strong guarantee: if push throws (full stack, or T's copy throws), *this is unchanged.
void push(const T &x)
{
if (items_.size() == N)
throw std::length_error("stack full");
items_.push_back(x); // no reallocation: a throwing copy leaves items_ as it was
}
BoundedStack, up to push code/bachelor-2/01-cpp-classes-raii/exercises/bounded_stack.hppThe full check comes before any change. The constructor reserves room for elements, so push_back never reallocates: it copies x into the free slot after the last element, and only then increases the size. If the copy throws, the size was not changed and no existing element was touched, so the stack is exactly as before: the strong guarantee. (A vector that had to grow would copy the old elements into a new block first, which is where a weaker implementation could lose them.) pop and top throw std::out_of_range on an empty stack.
Exercise 1.10 ★★★
Write a class TxnFile, a file that appears whole or not at all: the constructor creates path.tmp, write appends to it, commit() closes it and renames it to path. If the object dies without a commit (in particular during unwinding), the temporary file is removed and path is untouched. Which guarantee does a function that writes a report through a TxnFile give? What can still go wrong between the close and the rename, and why must the destructor not throw?
Solution
Solution of Exercise 1.10.
class TxnFile {
public:
explicit TxnFile(std::string path)
: path_(std::move(path)), tmp_(path_ + ".tmp"), f_(std::fopen(tmp_.c_str(), "w"))
{
if (f_ == nullptr)
throw std::runtime_error("cannot create " + tmp_);
}
~TxnFile()
{
if (f_ != nullptr)
std::fclose(f_);
if (!committed_)
std::remove(tmp_.c_str()); // unwinding or no commit: nothing appears
}
TxnFile(const TxnFile &) = delete;
TxnFile &operator=(const TxnFile &) = delete;
void write(const std::string &s)
{
if (std::fputs(s.c_str(), f_) == EOF)
throw std::runtime_error("write failed");
}
void commit()
{
int closed = std::fclose(f_);
f_ = nullptr;
if (closed != 0 || std::rename(tmp_.c_str(), path_.c_str()) != 0)
throw std::runtime_error("commit failed");
committed_ = true;
}
private:
std::string path_, tmp_;
std::FILE *f_;
bool committed_ = false;
};
TxnFile code/bachelor-2/01-cpp-classes-raii/exercises/txn_file.hppA function that writes its report through a TxnFile and commits at its end gives the strong guarantee for the file path: either the commit happened and the whole report is there, or the destructor removed the temporary and path is as before. Between the close and the rename, rename itself may fail (no permission on the directory, or path names a directory); then commit throws, the destructor removes the temporary, and path is untouched. A crash of the whole machine there leaves a stale path.tmp, but never a half file at path. The destructor runs during unwinding, when another exception is in flight; letting a second one out would end the program (destructors are noexcept), so it ignores the results of fclose and remove.
Exercise 1.11 ★★★
A function nests blocks; block acquires resource by constructing an RAII object , then opens block . The constructor of throws, for some , and a handler outside the function catches it. Prove which resources are released, in which order, and how many destructor calls run. What changes if instead the exception is thrown after is built, inside block ?
Solution
Solution of Exercise 1.11.
’s constructor did not finish, so never existed and has no destructor call (whatever part of it had acquired, it must release itself, for instance with members, as in Exercise 1.6). The exception leaves blocks in that order, and each destroys its object: , so are released, in that order, by destructor calls. were never acquired. If the exception comes after is built, all objects are alive, and unwinding destroys : calls, releasing first and last.
Exercise 1.12 ★★★
Write a class Matrix of doubles with rows and columns stored row by row in a std::vector<double>, whose invariant is data.size() == rows * cols. Give it a checked access m(i, j) in a const and a non-const version, transposed() and a product that throws std::invalid_argument on mismatched sizes. Prove that no public function can break the invariant.
Solution
Solution of Exercise 1.12.
// Invariant: rows_ >= 1, cols_ >= 1 and data_.size() == rows_ * cols_.
Matrix(std::size_t rows, std::size_t cols, double fill = 0.0)
: rows_(rows), cols_(cols), data_(checked(rows, cols), fill) {}
Matrix(const Matrix &) = default;
Matrix &operator=(Matrix other) noexcept // copy first, then swap: strong; no move
// (the declared copy constructor suppresses it)
{
std::swap(rows_, other.rows_);
std::swap(cols_, other.cols_);
data_.swap(other.data_);
return *this;
}
private:
static std::size_t checked(std::size_t rows, std::size_t cols)
{
if (rows == 0 || cols == 0)
throw std::invalid_argument("empty matrix");
return rows * cols;
}
std::size_t index(std::size_t r, std::size_t c) const
{
if (r >= rows_ || c >= cols_)
throw std::out_of_range("matrix index");
return r * cols_ + c;
}
std::size_t rows_, cols_;
std::vector<double> data_;
};
Matrix: construction, assignment and the checks code/bachelor-2/01-cpp-classes-raii/exercises/matrix.hppThe constructor establishes the invariant: checked throws before data_ is built when a size is 0, and otherwise data_ gets exactly elements. The three members are private, so only member functions can change them. Of those, operator() changes an element, never a size; transposed and operator* create new matrices through the constructor and do not change *this. The copy constructor copies a valid matrix member by member. The one danger is assignment: the implicit one would assign rows_, cols_, then data_, and if copying data_ ran out of memory, the new sizes would sit with the old data. The class therefore takes its argument by value (the copy is made first, and may throw before *this is touched) and swaps the three members, which cannot throw. No public function can break the invariant. Tested in tests/exercises_test.cpp.
1.6 Problem: A logger that never loses a line
Problem 1.1
Weekend problem — A logger that never loses a line
The weather station appends each batch of readings to its log with append_readings. The C version checks four things and returns early on each failure. Its C++ rewrite owns everything with objects and throws. Both were run on the same four cases: a log in a directory that does not exist, a batch containing the error code , a good batch, and a write to /dev/full, a Linux device on which every write fails as on a full disk.
int append_readings(const char *path, const double *t, int n)
{
FILE *f = fopen(path, "a");
if (f == NULL)
return -1; // check 1: cannot open
char *buf = malloc(16 * (size_t)n + 1);
if (buf == NULL)
return -2; // check 2: no memory
int len = 0;
for (int i = 0; i < n; i++) {
if (t[i] < -90.0)
return -3; // check 3: an error code in the data
len += snprintf(buf + len, 16, "%.1f\n", t[i]);
}
if (fputs(buf, f) == EOF || fflush(f) == EOF)
return -4; // check 4: the write failed
free(buf);
fclose(f);
return n;
}
int main(void)
{
double ok[] = {18.5, 19.25, 17.0}, bad[] = {18.5, -99.0, 17.0};
const char *paths[] = {"no_such_dir/w.log", "/dev/null", "/dev/null", "/dev/full"};
const double *data[] = {ok, bad, ok, ok};
for (int s = 0; s < 4; s++) {
int r = append_readings(paths[s], data[s], 3);
printf("%-18s returned %2d, open files now %d\n", paths[s], r, open_files());
}
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o logger logger.c -lm && ./logger
no_such_dir/w.log returned -1, open files now 3
/dev/null returned -3, open files now 4
/dev/null returned 3, open files now 4
/dev/full returned -4, open files now 5
void append_readings(const std::string &path, const std::vector<double> &t)
{
std::string buf; // owns its own memory
for (double x : t) {
if (x < -90.0)
throw std::invalid_argument("error code in the data");
char cell[16];
std::snprintf(cell, sizeof cell, "%.1f\n", x);
buf += cell;
}
File f(path, "a"); // throws if it cannot open
f.write(buf);
f.flush(); // throws if the disk is full
}
main runs the same four cases and catches std::exception code/bachelor-2/01-cpp-classes-raii/listings/raii_logger.cpp$ g++ -std=c++20 -O2 -Wall -Wextra -o raii_logger raii_logger.cpp && ./raii_logger
no_such_dir/w.log cannot open no_such_dir/w.log open files now 3
/dev/null error code in the data open files now 3
/dev/null ok open files now 3
/dev/full flush failed open files now 3
Part I — The C version.
- How many exit paths by
returndoes the Cappend_readingshave? - For each
return, list the resources held at that moment and those released. - Explain the four counts of open files in Output 1.12.
- How many bytes of heap memory did the four cases request and never free?
- Rewrite the end of the C function so that it has one exit point, with
gototo cleanup labels. How many labels are needed, and in what order are they placed? - With the notation of Exercise 1.8, give , and for this function, and the number of release calls its author should have written. How many did they write?
Part II — The C++ version.
- Which objects of the C++
append_readingsown a resource, and which resource? - Why does every count of open files in Output 1.13 stay at 3?
- The C++ version checks every reading before it opens the file, and writes the batch with one
write. What could the log contain after the second case if it wrote each reading as soon as it was checked? - List the ways out of the C++ function: the normal return and each throw, with the line that throws.
- How many release calls (
fclose,free,delete) appear in the C++append_readings? Where are the releases written? - When
flushthrows on/dev/full, which destructors run, and in which order?
Part III — Guarantees.
- Which exception-safety guarantee does the C++
append_readingsgive when the batch contains ? - Which guarantee does it give when the flush fails? Consider a disk that fills up after half a batch.
~Fileignores the result offclose. Why may it not throw, and why does the class offerflushfor that reason?- Make the function strong in all cases with the
TxnFileof Exercise 1.10: describe the steps, given that the log must be appended to, not replaced. - For a log of bytes and a batch of bytes, how many bytes does each version write?
- The station’s log holds 731 daily lines of 5 bytes each (such as
18.5and a newline); a batch is 3 lines. How many times more bytes does the strong version write? Is it worth it once a day?
Part IV — The price of a throw.
- In Output 1.9, compare the success path with and without exceptions.
- Compare the failure path. How many failed return codes cost as much as one throw, in that run?
- The station appends a batch every minute and 1 % of the batches fail. Estimate the time spent throwing in a year, with one microsecond per throw.
- A validator of fields, 30 % of them invalid, throws once per invalid field. Estimate the time spent on throws, and compare with returning an error value.
- Which of the two programs should use exceptions for its failures, following the “in practice” box?
- State the result of the problem: the number of exit paths of a function with checks, the number of releases on each with RAII and how many are written by hand, and the measured price of a throw.
Solution
Solution of Problem 1.1.
1. Five: the four early returns to and the final return n, that is with .
2. : nothing is held (fopen failed). : f is held and not closed. and : f and buf are held, neither released. return n: both are released.
3. 3: the open failed, nothing leaked. 4: the case returned and leaked its FILE for /dev/null. 4: the good batch released everything. 5: /dev/full returned and leaked one more.
4. Each malloc asked for bytes, lost in cases 2 and 4: 98 bytes (without counting the memory of the two leaked FILEs).
5. Keep the result in a variable and jump to labels placed in the reverse order of acquisition: free_buf: (free(buf);) before close_file: (fclose(f);), then one return result;. Check 2 jumps to close_file, checks 3 and 4 to free_buf: two labels.
6. , , : release calls were needed; the author wrote 2, both on the final path.
7. buf, a std::string, owns its heap memory; f, a File, owns the FILE and the open file. (cell is an array in the frame: no resource.)
8. In case 1 the File constructor threw because fopen failed, so nothing was opened. In case 2 the function threw before f existed. In case 3 f died at the end of the function. In case 4 the throw from flush unwound the function and destroyed f, which closed the file. No path leaves a file open.
9. It would have written 18.5 before meeting : a half batch at the end of the log, with no sign that it is incomplete. Checking everything first and writing once leaves the log as it was.
10. The end of the body (line 23); the throw of line 15; the File constructor’s throw at line 20; write at line 21; flush at line 22. A std::bad_alloc from buf += cell (line 18) is possible too.
11. None. The releases are written once, in ~File (its fclose) and in the destructor of std::string.
12. f, built after buf, is destroyed first and closes the file; then buf frees its memory; then the handler in main runs.
13. The strong guarantee: the function threw before opening the file, so the log and everything else are as before the call.
14. Only the basic one: nothing leaks and the File is closed, but on a disk that fills during the write, part of the batch may already be in the log. (/dev/full accepts nothing, which hides this.)
15. A destructor is noexcept: an exception leaving it calls std::terminate, and it may be running during the unwinding of another exception. So ~File cannot report a failed fclose. A caller who must know whether the data reached the file calls flush while the object is alive, where a throw is allowed; the close that follows has nothing left to write.
16. Open a TxnFile on the log’s name, copy the current log into it, append the batch, then commit, which renames the copy over the log. If anything throws before the rename, the temporary is removed and the log is untouched; after the rename, the log holds the old lines and the whole batch.
17. The plain version writes bytes; the strong one writes .
18. and : times more. Once a day, 3.7 kB is nothing for a disk: the strong version is worth it.
19. Both success timings are below a nanosecond and differ by noise only: being able to throw costs nothing measurable when nothing is thrown.
20. A failed return code costs about as much as a success, below a nanosecond; a throw and its catch cost several hundred nanoseconds. In that run, failed return codes cost as much as one throw (the last line prints 1352): of the order of a thousand.
21. batches a year, of which 5256 fail: about milliseconds of throwing in a year.
22. throws at about a microsecond: about 30 seconds, against a few hundredths of a second with error values, a thousand times less.
23. The logger: its failures are rare and handled far from where they occur. The validator should return an error value per field: an invalid field is a normal outcome there.
24. A function with checks has exit paths by return (more with exceptions). With every resource owned by an object, each acquired resource is released exactly once on each path, and no release is written in the function itself: 0 instead of (7 for the logger, which wrote 2). On the author’s laptop the success path costs the same with or without exceptions, below a nanosecond, while a throw costs several hundred nanoseconds, about a thousand failed return codes.