---
title: "From C to C++: Classes and Resource Management"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 1
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 1 — From 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](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#ch-b2-files-pipes-signals) explains these numbers).

```c
// 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;
}
```

***Listing 1.1.** A header check with two early returns code/bachelor-2/01-cpp-classes-raii/listings/early_return.c*

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

***Output 1.1.** Ten calls, ten files left open.*

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 `return`s, 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](#def-b2-cpp-classes-raii-class) 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](#def-b2-cpp-classes-raii-class)* (the school volumes, in Python) groups data and the methods that use them, and its [constructor](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-class) of type `T`. It is bound once, when it is declared, and never rebound; reading or assigning the reference reads or assigns the [object](#def-b2-cpp-classes-raii-class) it names. A reference cannot be null. A *const reference* `const T &` names the [object](#def-b2-cpp-classes-raii-class) but allows only reading it.

A [reference](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-class) 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](https://one-course.com/books/computer-science/4/en/chapter/5-the-standard-library-containers-iterators-and-algorithms#ch-b2-cpp-standard-library) opens them. Output goes through `std::cout <<`, which is overloaded for every type it can print.

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

***Listing 1.2.** [References](#def-b2-cpp-classes-raii-reference), overloading, a [namespace](#def-b2-cpp-classes-raii-namespace), strings and vectors code/bachelor-2/01-cpp-classes-raii/listings/references.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o references references.cpp && ./references
x = 2, y = 10
9 9
4 streets, 42 letters
```

***Output 1.2.** The swap went through the [references](#def-b2-cpp-classes-raii-reference).*

**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, $3 \times 3$ and $2 \times 4.5$, 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 $9 + 12 + 14 + 7$ make 42.

A `const` [reference](#def-b2-cpp-classes-raii-reference) promises that the function will not change the [object](#def-b2-cpp-classes-raii-class). The promise is checked by the compiler, so breaking it is an error, not a run-time surprise.

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

***Listing 1.3.** Writing through a const [reference](#def-b2-cpp-classes-raii-reference) (an error on purpose) code/bachelor-2/01-cpp-classes-raii/listings/const_error.cpp*

```
$ 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]
```

***Output 1.3.** The compiler refuses, and names the line and the [reference](#def-b2-cpp-classes-raii-reference).*

## 1.2 Classes

A C structure groups data, and any function may change its fields. A C++ [class](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-class)’s declarations into those any code may use and those only the [class](#def-b2-cpp-classes-raii-class)’s own [member functions](#def-b2-cpp-classes-raii-class) may use. A `class` starts private, a `struct` public, for its members and for its base classes ([Chapter 3](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#ch-b2-cpp-polymorphism)); otherwise the two keywords are the same.

**Definition 1.6 (Constructor, destructor).**

A *constructor* of a [class](#def-b2-cpp-classes-raii-class) `C` is a [member function](#def-b2-cpp-classes-raii-class) named `C`, without a return type, that the compiler calls each time an [object](#def-b2-cpp-classes-raii-class) of `C` is created; its *member initialiser list* (after the `:`) gives each [data member](#def-b2-cpp-classes-raii-class) its first value. The *destructor* `~C()` is the [member function](#def-b2-cpp-classes-raii-class) the compiler calls when the [object](#def-b2-cpp-classes-raii-class)’s lifetime ends; a [class](#def-b2-cpp-classes-raii-class) has exactly one.

The [constructor](#def-b2-cpp-classes-raii-constructor) is the only way in: there is no [object](#def-b2-cpp-classes-raii-class) of `C` that a [constructor](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-class) that every [constructor](#def-b2-cpp-classes-raii-constructor) establishes and every public [member function](#def-b2-cpp-classes-raii-class) preserves. A [constructor](#def-b2-cpp-classes-raii-constructor) that cannot establish it does not return: it reports the failure ([Section 1.4](#sec-1-4)), and no [object](#def-b2-cpp-classes-raii-class) exists.

If the [data members](#def-b2-cpp-classes-raii-class) are private, only the [class](#def-b2-cpp-classes-raii-class)’s own functions can break the invariant, so checking it is a matter of reading one [class](#def-b2-cpp-classes-raii-class), not the whole program. The [class](#def-b2-cpp-classes-raii-class) below keeps a fraction in lowest terms with a positive denominator, so that two equal fractions have equal members.

```cpp
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_;
};
```

***Listing 1.4.** A fraction that is always in lowest terms code/bachelor-2/01-cpp-classes-raii/listings/fraction.hpp*

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

***Listing 1.5.** Using it; the [constructor](#def-b2-cpp-classes-raii-constructor) refuses a zero denominator code/bachelor-2/01-cpp-classes-raii/listings/fraction_demo.cpp*

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

***Output 1.4.** Every printed fraction satisfies the invariant.*

**Example 1.8 (Building 6/(−8)6/(-8)6/(−8)).**

The initialiser list sets `num_ = 6`, `den_ = -8`. The body finds `den_` nonzero and negative, so it negates both, $-6/8$, then divides both by $\gcd(-6, 8) = 2$ (`std::gcd` returns a non-negative result): $-3/4$. The sum `a + b` is built by the [constructor](#def-b2-cpp-classes-raii-constructor) too, from $(-3)\cdot 4 + 1 \cdot 4 = -8$ over $16$, and comes out as $-1/2$. The expression `a + 1` works because `Fraction(long whole)` is a [constructor](#def-b2-cpp-classes-raii-constructor) with one argument: the compiler uses it to convert `1` into $1/1$. 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](#def-b2-cpp-classes-raii-class) declared with `const` after its parameter list is a *const member function*: it may not change the [object](#def-b2-cpp-classes-raii-class)’s [data members](#def-b2-cpp-classes-raii-class), and it is the only kind of [member function](#def-b2-cpp-classes-raii-class) that can be called on a `const` [object](#def-b2-cpp-classes-raii-class) or through a `const` [reference](#def-b2-cpp-classes-raii-reference). A program is *const-correct* when every function that does not change an [object](#def-b2-cpp-classes-raii-class) takes it as `const`, and every [member function](#def-b2-cpp-classes-raii-class) that does not change its [object](#def-b2-cpp-classes-raii-class) is `const`.

In [Listing 1.4](#lst-b2-cpp-classes-raii-fraction), `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](#def-b2-cpp-classes-raii-const) spreads: once `operator<<` takes its fraction by `const` [reference](#def-b2-cpp-classes-raii-reference), the accessors it calls must be const.

## 1.3 Resource acquisition is initialisation

An automatic [object](#def-b2-cpp-classes-raii-class) of a [class](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-constructor) at that end. The [class](#def-b2-cpp-classes-raii-class) `Noisy` prints a line in its [constructor](#def-b2-cpp-classes-raii-constructor) and one in its [destructor](#def-b2-cpp-classes-raii-constructor), so that a run shows every lifetime.

```cpp
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_;
};
```

***Listing 1.6.** An [object](#def-b2-cpp-classes-raii-class) that reports its birth and its death code/bachelor-2/01-cpp-classes-raii/listings/noisy.hpp*

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

***Listing 1.7.** Nested scopes and a loop code/bachelor-2/01-cpp-classes-raii/listings/lifetimes.cpp*

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

***Output 1.5.** Each scope destroys its [objects](#def-b2-cpp-classes-raii-class) when it ends, the last made first.*

The language fixes the order: when a block ends, its automatic [objects](#def-b2-cpp-classes-raii-class) are destroyed in the reverse order of their construction, and an [object](#def-b2-cpp-classes-raii-class)’s members are destroyed after its [destructor](#def-b2-cpp-classes-raii-constructor)’s body, in the reverse order of their declaration.

[Objects](#def-b2-cpp-classes-raii-class) declared outside every function (global [objects](#def-b2-cpp-classes-raii-class)) are built before `main` starts and destroyed after it returns, also in reverse order.

**Proposition 1.10 (Lifetimes nest).**

Let $a$ and $b$ be automatic [objects](#def-b2-cpp-classes-raii-class) of one thread, with $a$ constructed before $b$ and both alive at some moment. Then $b$ is destroyed before $a$. In other words, the lifetimes of automatic [objects](#def-b2-cpp-classes-raii-class) are nested intervals: two of them are either disjoint or one contains the other.

**Proof.** Let $A$ and $B$ be the blocks that declare $a$ and $b$. 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 $b$ is constructed, $a$ is alive, so $A$ is still active. Either $B = A$: then $b$ was declared after $a$ in the same block, and the block destroys them in reverse order, $b$ first. Or $B \neq A$: then $B$ was entered after $A$ and while $A$ was active, so $B$ is left first, and $b$ dies when $B$ is left, while $a$ waits for $A$. In both cases $b$ 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.

![The six objects of , each drawn from the output line that makes it to the line that drops it. Any two bars are either disjoint (d0 and d1, born in two iterations of the loop) or nested (c inside b2 inside b1 inside a).](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-classes-raii/fig-ac9959901386.svg)

*The six [objects](#def-b2-cpp-classes-raii-class) of [Listing 1.7](#lst-b2-cpp-classes-raii-lifetimes), each drawn from the output line that makes it to the line that drops it. Any two bars are either disjoint (`d0` and `d1`, born in two iterations of the loop) or nested (`c` inside `b2` inside `b1` inside `a`).*

A [destructor](#def-b2-cpp-classes-raii-constructor) 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](#def-b2-cpp-classes-raii-constructor) of an [object](#def-b2-cpp-classes-raii-class) that owns it, and released by that [object](#def-b2-cpp-classes-raii-class)’s [destructor](#def-b2-cpp-classes-raii-constructor).

**Method 1.12 (Owning a resource with an object).**

To make a [resource](#def-b2-cpp-classes-raii-raii) safe:

1. write a [class](#def-b2-cpp-classes-raii-class) whose [constructor](#def-b2-cpp-classes-raii-constructor) acquires the [resource](#def-b2-cpp-classes-raii-raii) and fails (throws, [Section 1.4](#sec-1-4) ) if it cannot, so that every [object](#def-b2-cpp-classes-raii-class) of the [class](#def-b2-cpp-classes-raii-class) holds a [resource](#def-b2-cpp-classes-raii-raii) ;
2. release the [resource](#def-b2-cpp-classes-raii-raii) in the [destructor](#def-b2-cpp-classes-raii-constructor) , and nowhere else;
3. forbid copying ( `= delete` ), so that one [resource](#def-b2-cpp-classes-raii-raii) has one owner ( [Chapter 2](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#ch-b2-cpp-copy-move) shows how ownership can move instead);
4. give the [class](#def-b2-cpp-classes-raii-class) the operations the program needs, and use it as an automatic [object](#def-b2-cpp-classes-raii-class) or a [data member](#def-b2-cpp-classes-raii-class) , never with a raw `fopen` , `malloc` or `new` in the code that uses it.

```cpp
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_;
};
```

***Listing 1.8.** A file owned by an [object](#def-b2-cpp-classes-raii-class) code/bachelor-2/01-cpp-classes-raii/listings/file_handle.hpp*

The [class](#def-b2-cpp-classes-raii-class) follows the four steps: the [constructor](#def-b2-cpp-classes-raii-constructor) opens or throws, the [destructor](#def-b2-cpp-classes-raii-constructor) 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`.

```cpp
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
}
```

***Listing 1.9.** The header check with RAII; `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
```

***Output 1.6.** Three files open before, three after.*

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](#def-b2-cpp-classes-raii-constructor) closes the file on whichever path is taken. A missing file is no longer a return value to check: the [constructor](#def-b2-cpp-classes-raii-constructor) throws, `main` catches, and no `File` without a file ever exists. The drawing shows what `f` is in memory.

![A 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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-classes-raii/fig-f2832d8792d4.svg)

*A `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](#def-b2-cpp-classes-raii-constructor) 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](#def-b2-cpp-classes-raii-raii) are all owned by automatic RAII [objects](#def-b2-cpp-classes-raii-class) (or by members of such [objects](#def-b2-cpp-classes-raii-class)), each [resource](#def-b2-cpp-classes-raii-raii) that was acquired is released exactly once, whatever path the function leaves by: a `return`, the end of the body, or an [exception](#def-b2-cpp-classes-raii-exception) ([Section 1.4](#sec-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](#def-b2-cpp-classes-raii-raii) it acquires directly: by the method, the acquisition is the construction of an [object](#def-b2-cpp-classes-raii-class) $o$ declared in the block. If the [constructor](#def-b2-cpp-classes-raii-constructor) fails, $o$ never existed and nothing was acquired, so nothing must be released. If it succeeds, $o$ 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](#def-b2-cpp-classes-raii-exception) crossing it) ends $o$’s lifetime, and the compiler then calls the [destructor](#def-b2-cpp-classes-raii-constructor) once, which releases the [resource](#def-b2-cpp-classes-raii-raii) once. Copies are deleted, so no second [object](#def-b2-cpp-classes-raii-class) releases it. [Resources](#def-b2-cpp-classes-raii-raii) acquired in inner blocks are released by the induction hypothesis, before the block is left, and [resources](#def-b2-cpp-classes-raii-raii) held by members of $o$ are released when $o$’s members are destroyed. The outermost block is the function body, which gives the claim. ∎

## 1.4 Exceptions

A [constructor](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-exception).

**Definition 1.14 (Exception, throw, handler).**

An *exception* is an [object](#def-b2-cpp-classes-raii-class) 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](#def-b2-cpp-classes-raii-exception) 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](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#ch-b2-cpp-polymorphism) 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](#def-b2-cpp-classes-raii-class) of each block left is destroyed, in the reverse order of construction, as if its block had ended.

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

***Listing 1.10.** A throw three calls deep code/bachelor-2/01-cpp-classes-raii/listings/unwind.cpp*

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

***Output 1.7.** The [destructors](#def-b2-cpp-classes-raii-constructor) run before the [handlers](#def-b2-cpp-classes-raii-exception) do.*

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](#prop-b2-cpp-classes-raii-every-path) is why this matters: an [exception](#def-b2-cpp-classes-raii-exception) is one more way out of a block, and the [destructors](#def-b2-cpp-classes-raii-constructor) take it as well.

![The frames of when 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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-classes-raii/fig-8f345475cb6e.svg)

*The frames of [Listing 1.10](#lst-b2-cpp-classes-raii-unwind) when `parse(3)` throws, the newest on top. Unwinding pops frames downward to the frame whose `try` block has a matching handler, destroying each [object](#def-b2-cpp-classes-raii-class) it passes, then runs the handler.*

An [exception](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-raii) is leaked and every [object](#def-b2-cpp-classes-raii-class) 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](#def-b2-cpp-classes-raii-exception) tries to leave a `noexcept` function, the program is ended by `std::terminate`; [destructors](#def-b2-cpp-classes-raii-constructor) are `noexcept` unless declared otherwise, which is why a [destructor](#def-b2-cpp-classes-raii-constructor) must never let an [exception](#def-b2-cpp-classes-raii-exception) out.

The two [member functions](#def-b2-cpp-classes-raii-class) 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.

```cpp
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"};
};
```

***Listing 1.11.** The same operation with the basic and with the strong guarantee code/bachelor-2/01-cpp-classes-raii/listings/guarantee.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o guarantee guarantee.cpp && ./guarantee
basic:  empty name, size now 4
strong: empty name, size now 2
```

***Output 1.8.** The basic version kept two of the four new names; the strong one kept none.*

Both versions leak nothing (the vectors and strings own their memory) and leave a valid roster, so both give the [basic guarantee](#def-b2-cpp-classes-raii-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.

![The roster of before the call and after a call throws on the empty name. The basic guarantee leaves some valid state, here with Cora and Dev added; the strong guarantee leaves the state of before.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-classes-raii/fig-3bf77c52aad0.svg)

*The roster of [Listing 1.11](#lst-b2-cpp-classes-raii-guarantee) before the call and after a call throws on the empty name. The [basic guarantee](#def-b2-cpp-classes-raii-guarantee) leaves some valid state, here with `Cora` and `Dev` added; the strong guarantee leaves the state of before.*

A thrown [exception](#def-b2-cpp-classes-raii-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.

```cpp
__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);
```

***Listing 1.12.** Timing failures reported two ways (`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
```

***Output 1.9.** One run on the author’s laptop; the digits change from run to run.*

The success path costs the same whether the function may throw or not: with this compiler, the code that handles an [exception](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-exception) [object](#def-b2-cpp-classes-raii-class) is allocated, the frames are searched for a handler, and the stack is unwound. [Exceptions](#def-b2-cpp-classes-raii-exception) 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](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-raii) with an [object](#def-b2-cpp-classes-raii-class), 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](#lst-b2-cpp-classes-raii-noisy)).

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

***Listing 1.13.** Who is made and dropped, and when code/bachelor-2/01-cpp-classes-raii/listings/exo_order.cpp*

**Solution of Exercise 1.1.**

The global [object](#def-b2-cpp-classes-raii-class) 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
```

***Output 1.14.** The ten lines.*

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

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

***Listing 1.14.** The longer name code/bachelor-2/01-cpp-classes-raii/listings/exo_dangling.cpp*

```
$ 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]
```

***Output 1.10.** The warning; the run that follows prints nothing: it is killed by signal 11, a segmentation fault, which the capture tool records as status $-11$.*

**Solution of Exercise 1.2.**

`result` is an automatic [object](#def-b2-cpp-classes-raii-class) of `longer`: it dies when `longer` returns, so the returned [reference](#def-b2-cpp-classes-raii-reference) names an [object](#def-b2-cpp-classes-raii-class) that no longer exists (a *dangling* [reference](#def-b2-cpp-classes-raii-reference)), and reading it in `main` is undefined behaviour. Any outcome is allowed; this compiler, knowing the [reference](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-reference) would also be correct, since they name the caller’s [objects](#def-b2-cpp-classes-raii-class), but only as long as those outlive the use.)

**Exercise 1.3 ★.**

Write a [class](#def-b2-cpp-classes-raii-class) `IntArray` that owns a heap array of `n` ints, zero-filled, given to its [constructor](#def-b2-cpp-classes-raii-constructor): `size()`, `at(i)` returning a [reference](#def-b2-cpp-classes-raii-reference) (with a const version for const arrays), throwing `std::out_of_range` when $i \geq n$, and no copies. Which step of [Method 1.12](#met-b2-cpp-classes-raii-raii) does each part of your [class](#def-b2-cpp-classes-raii-class) implement?

**Solution of Exercise 1.3.**

```cpp
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.hpp*

Step 1: the [constructor](#def-b2-cpp-classes-raii-constructor) acquires the block (`new int[n]{}` zero-fills it, and throws `std::bad_alloc` if there is no memory, so no [object](#def-b2-cpp-classes-raii-class) without a block exists). Step 2: the [destructor](#def-b2-cpp-classes-raii-constructor)’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 $n$ nested blocks, and block $j$ (for $j = 1, \dots, n$, from the outermost) declares $m$ `Noisy` [objects](#def-b2-cpp-classes-raii-class) named `j.1`, …, `j.m` before it opens block $j+1$. 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](#prop-b2-cpp-classes-raii-reverse-order).

**Solution of Exercise 1.4.**

Each of the $nm$ [objects](#def-b2-cpp-classes-raii-class) prints one `make` and one `drop` line: $2nm$ lines. When `n.m` is made, all $nm$ [objects](#def-b2-cpp-classes-raii-class) are alive (the blocks are nested and none has ended), so by [Proposition 1.10](#prop-b2-cpp-classes-raii-reverse-order) 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 $m \geq 3$).

**Exercise 1.5 ★★.**

Predict the output of the program below, which throws a different [exception](#def-b2-cpp-classes-raii-exception) for each $k$ through three levels of [handlers](#def-b2-cpp-classes-raii-exception). Name, for each $k$, the handler that catches and the rule that decides it.

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

***Listing 1.15.** Three levels of [handlers](#def-b2-cpp-classes-raii-exception) code/bachelor-2/01-cpp-classes-raii/listings/exo_handlers.cpp*

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

***Output 1.15.** The output.*

$k = 0$: nothing thrown. $k = 1$: `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. $k = 2$: the first inner handler matches; the [exception](#def-b2-cpp-classes-raii-exception) is finished, so `step` goes on and prints `step done`. $k = 3$: `runtime_error` matches neither inner handler nor `logic_error`; the outer `std::exception` handler catches it. $k = 4$: an `int` is not a [class](#def-b2-cpp-classes-raii-class) derived from `std::exception`; only `catch (...)` matches.

**Exercise 1.6 ★★.**

The [class](#def-b2-cpp-classes-raii-class) `Merger` opens two files in its [constructor](#def-b2-cpp-classes-raii-constructor) and closes them in its [destructor](#def-b2-cpp-classes-raii-constructor). Explain the output, then fix the [class](#def-b2-cpp-classes-raii-class) with [Method 1.12](#met-b2-cpp-classes-raii-raii), without writing a [destructor](#def-b2-cpp-classes-raii-constructor).

```cpp
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_;
};
```

***Listing 1.16.** A [constructor](#def-b2-cpp-classes-raii-constructor) that acquires two [resources](#def-b2-cpp-classes-raii-raii) code/bachelor-2/01-cpp-classes-raii/listings/exo_two_files.cpp*

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

***Output 1.11.** Five failures.*

**Solution of Exercise 1.6.**

Each time, the first `fopen` succeeds, the second fails, and the [constructor](#def-b2-cpp-classes-raii-constructor) throws. A [constructor](#def-b2-cpp-classes-raii-constructor) that throws never produces an [object](#def-b2-cpp-classes-raii-class), so the [destructor](#def-b2-cpp-classes-raii-constructor) never runs, and the raw pointer `a_` has no [destructor](#def-b2-cpp-classes-raii-constructor) of its own: one file leaks per failure, 4, 5, …, 8 open files. The fix makes each file a member that owns itself:

```cpp
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.hpp*

When `b_`’s [constructor](#def-b2-cpp-classes-raii-constructor) throws, the members already built (here `a_`) are destroyed before the [exception](#def-b2-cpp-classes-raii-exception) leaves the [constructor](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-class) template `ScopeGuard<F>` whose [constructor](#def-b2-cpp-classes-raii-constructor) takes a callable `action` and whose [destructor](#def-b2-cpp-classes-raii-constructor) 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 `malloc`s, an `fopen`) one cleanup on every path, and why `dismiss` is needed when the function succeeds and hands the [resources](#def-b2-cpp-classes-raii-raii) to its caller. (Write `ScopeGuard g([&] {free(p);});`: C++17 deduces `F`.)

**Solution of Exercise 1.7.**

```cpp
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.hpp*

In 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](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-raii) 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 $r$ [resources](#def-b2-cpp-classes-raii-raii), in order, and contains $k$ checks, check $i$ coming after the first $a_i$ acquisitions ($0 \le a_1 \le \dots \le a_k \le r$), each of which returns early. Show that it has $k + 1$ exit paths by return. Written in C, how many release calls must its author write so that nothing leaks? Written with one RAII [object](#def-b2-cpp-classes-raii-class) per [resource](#def-b2-cpp-classes-raii-raii), how many, and why does [Proposition 1.13](#prop-b2-cpp-classes-raii-every-path) make this count right?

**Solution of Exercise 1.8.**

Each of the $k$ checks has its `return`, and the end of the body is one more: $k + 1$ paths. In C, path $i$ must release the $a_i$ [resources](#def-b2-cpp-classes-raii-raii) held at check $i$, and the last path all $r$: the author writes $a_1 + \dots + a_k + r$ release calls. With one RAII [object](#def-b2-cpp-classes-raii-class) per [resource](#def-b2-cpp-classes-raii-raii), the function contains none: the release is written once, in each [class](#def-b2-cpp-classes-raii-class)’s [destructor](#def-b2-cpp-classes-raii-constructor). By [Proposition 1.13](#prop-b2-cpp-classes-raii-every-path), on path $i$ exactly the $a_i$ [objects](#def-b2-cpp-classes-raii-class) 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 $N$ 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 of Exercise 1.9.**

```cpp
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.hpp*

The full check comes before any change. The [constructor](#def-b2-cpp-classes-raii-constructor) reserves room for $N$ 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](#def-b2-cpp-classes-raii-class) `TxnFile`, a file that appears whole or not at all: the [constructor](#def-b2-cpp-classes-raii-constructor) creates `path.tmp`, `write` appends to it, `commit()` closes it and renames it to `path`. If the [object](#def-b2-cpp-classes-raii-class) 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](#def-b2-cpp-classes-raii-constructor) not throw?

**Solution of Exercise 1.10.**

```cpp
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.hpp*

A 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](#def-b2-cpp-classes-raii-constructor) 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](#def-b2-cpp-classes-raii-constructor) 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](#def-b2-cpp-classes-raii-constructor) runs during unwinding, when another [exception](#def-b2-cpp-classes-raii-exception) is in flight; letting a second one out would end the program ([destructors](#def-b2-cpp-classes-raii-constructor) are `noexcept`), so it ignores the results of `fclose` and `remove`.

**Exercise 1.11 ★★★.**

A function nests $n$ blocks; block $j$ acquires [resource](#def-b2-cpp-classes-raii-raii) $R_j$ by constructing an RAII [object](#def-b2-cpp-classes-raii-class) $o_j$, then opens block $j+1$. The [constructor](#def-b2-cpp-classes-raii-constructor) of $o_k$ throws, for some $1 \le k \le n$, and a handler outside the function catches it. Prove which [resources](#def-b2-cpp-classes-raii-raii) are released, in which order, and how many [destructor](#def-b2-cpp-classes-raii-constructor) calls run. What changes if instead the [exception](#def-b2-cpp-classes-raii-exception) is thrown after $o_n$ is built, inside block $n$?

**Solution of Exercise 1.11.**

$o_k$’s [constructor](#def-b2-cpp-classes-raii-constructor) did not finish, so $o_k$ never existed and has no [destructor](#def-b2-cpp-classes-raii-constructor) call (whatever part of $R_k$ it had acquired, it must release itself, for instance with members, as in [Exercise 1.6](#exo-b2-cpp-classes-raii-6)). The [exception](#def-b2-cpp-classes-raii-exception) leaves blocks $k, k-1, \dots, 1$ in that order, and each destroys its [object](#def-b2-cpp-classes-raii-class): $o_{k-1}, \dots, o_1$, so $R_{k-1}, \dots, R_1$ are released, in that order, by $k - 1$ [destructor](#def-b2-cpp-classes-raii-constructor) calls. $R_{k+1}, \dots, R_n$ were never acquired. If the [exception](#def-b2-cpp-classes-raii-exception) comes after $o_n$ is built, all $n$ [objects](#def-b2-cpp-classes-raii-class) are alive, and unwinding destroys $o_n, \dots, o_1$: $n$ calls, releasing $R_n$ first and $R_1$ last.

**Exercise 1.12 ★★★.**

Write a [class](#def-b2-cpp-classes-raii-class) `Matrix` of `double`s with $r \geq 1$ rows and $c \geq 1$ 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 of Exercise 1.12.**

```cpp
    // 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.hpp*

The [constructor](#def-b2-cpp-classes-raii-constructor) establishes the invariant: `checked` throws before `data_` is built when a size is 0, and otherwise `data_` gets exactly $rc$ elements. The three members are private, so only [member functions](#def-b2-cpp-classes-raii-class) can change them. Of those, `operator()` changes an element, never a size; `transposed` and `operator*` create new matrices through the [constructor](#def-b2-cpp-classes-raii-constructor) and do not change `*this`. The copy [constructor](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-class) 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 $-99.0$, a good batch, and a write to `/dev/full`, a Linux device on which every write fails as on a full disk.

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

***Listing 1.17.** The C version code/bachelor-2/01-cpp-classes-raii/listings/logger.c*

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

***Output 1.12.** The C version on the four cases.*

```cpp
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
}
```

***Listing 1.18.** The C++ version; its `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
```

***Output 1.13.** The C++ version on the same cases.*

**Part I — The C version.**

1. How many exit paths by `return` does the C `append_readings` have?
2. For each `return` , list the [resources](#def-b2-cpp-classes-raii-raii) held at that moment and those released.
3. Explain the four counts of open files in [Output 1.12](#out-b2-cpp-classes-raii-logger-c) .
4. How many bytes of heap memory did the four cases request and never free?
5. Rewrite the end of the C function so that it has one exit point, with `goto` to cleanup labels. How many labels are needed, and in what order are they placed?
6. With the notation of [Exercise 1.8](#exo-b2-cpp-classes-raii-8) , give $r$ , $k$ and $a_1, \dots, a_k$ for this function, and the number of release calls its author should have written. How many did they write?

**Part II — The C++ version.**

7. Which [objects](#def-b2-cpp-classes-raii-class) of the C++ `append_readings` own a [resource](#def-b2-cpp-classes-raii-raii) , and which [resource](#def-b2-cpp-classes-raii-raii) ?
8. Why does every count of open files in [Output 1.13](#out-b2-cpp-classes-raii-logger-cpp) stay at 3?
9. 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?
10. List the ways out of the C++ function: the normal return and each throw, with the line that throws.
11. How many release calls ( `fclose` , `free` , `delete` ) appear in the C++ `append_readings` ? Where are the releases written?
12. When `flush` throws on `/dev/full` , which [destructors](#def-b2-cpp-classes-raii-constructor) run, and in which order?

**Part III — Guarantees.**

13. Which [exception-safety guarantee](#def-b2-cpp-classes-raii-guarantee) does the C++ `append_readings` give when the batch contains $-99.0$ ?
14. Which guarantee does it give when the flush fails? Consider a disk that fills up after half a batch.
15. `~File` ignores the result of `fclose` . Why may it not throw, and why does the [class](#def-b2-cpp-classes-raii-class) offer `flush` for that reason?
16. Make the function strong in all cases with the `TxnFile` of [Exercise 1.10](#exo-b2-cpp-classes-raii-10) : describe the steps, given that the log must be appended to, not replaced.
17. For a log of $L$ bytes and a batch of $b$ bytes, how many bytes does each version write?
18. The station’s log holds 731 daily lines of 5 bytes each (such as `18.5` and 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.**

19. In [Output 1.9](#out-b2-cpp-classes-raii-cost) , compare the success path with and without [exceptions](#def-b2-cpp-classes-raii-exception) .
20. Compare the failure path. How many failed return codes cost as much as one throw, in that run?
21. 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.
22. A validator of $10^8$ fields, 30 % of them invalid, throws once per invalid field. Estimate the time spent on throws, and compare with returning an error value.
23. Which of the two programs should use [exceptions](#def-b2-cpp-classes-raii-exception) for its failures, following the “in practice” box?
24. State the result of the problem: the number of exit paths of a function with $k$ checks, the number of releases on each with RAII and how many are written by hand, and the measured price of a throw.

**Solution of Problem 1.1.**

**1.** Five: the four early returns $-1$ to $-4$ and the final `return n`, that is $k + 1$ with $k = 4$.

**2.** $-1$: nothing is held (`fopen` failed). $-2$: `f` is held and not closed. $-3$ and $-4$: `f` and `buf` are held, neither released. `return n`: both are released.

**3.** 3: the open failed, nothing leaked. 4: the $-99.0$ case returned $-3$ and leaked its `FILE` for `/dev/null`. 4: the good batch released everything. 5: `/dev/full` returned $-4$ and leaked one more.

**4.** Each `malloc` asked for $16 \cdot 3 + 1 = 49$ bytes, lost in cases 2 and 4: 98 bytes (without counting the memory of the two leaked `FILE`s).

**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.** $r = 2$, $k = 4$, $(a_1, a_2, a_3, a_4) = (0, 1, 2, 2)$: $0 + 1 + 2 + 2 + 2 = 7$ 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](#def-b2-cpp-classes-raii-raii).)

**8.** In case 1 the `File` [constructor](#def-b2-cpp-classes-raii-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 $-99.0$: 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](#def-b2-cpp-classes-raii-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](#def-b2-cpp-classes-raii-constructor) 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](#def-b2-cpp-classes-raii-constructor) is `noexcept`: an [exception](#def-b2-cpp-classes-raii-exception) leaving it calls `std::terminate`, and it may be running during the unwinding of another [exception](#def-b2-cpp-classes-raii-exception). So `~File` cannot report a failed `fclose`. A caller who must know whether the data reached the file calls `flush` while the [object](#def-b2-cpp-classes-raii-class) 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 $b$ bytes; the strong one writes $L + b$.

**18.** $L = 731 \times 5 = 3655$ and $b = 15$: $(3655 + 15)/15 \approx 245$ 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, $786 / 0.582 \approx 1350$ failed return codes cost as much as one throw (the last line prints 1352): of the order of a thousand.

**21.** $365 \times 24 \times 60 = 525\,600$ batches a year, of which 5256 fail: about $5$ milliseconds of throwing in a year.

**22.** $3 \times 10^7$ 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 $k$ checks has $k + 1$ exit paths by return (more with [exceptions](#def-b2-cpp-classes-raii-exception)). With every [resource](#def-b2-cpp-classes-raii-raii) owned by an [object](#def-b2-cpp-classes-raii-class), each acquired [resource](#def-b2-cpp-classes-raii-raii) is released exactly once on each path, and no release is written in the function itself: 0 instead of $a_1 + \dots + a_k + r$ (7 for the logger, which wrote 2). On the author’s laptop the success path costs the same with or without [exceptions](#def-b2-cpp-classes-raii-exception), below a nanosecond, while a throw costs several hundred nanoseconds, about a thousand failed return codes.*
