---
title: "Copying, Moving and Smart Pointers"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 2
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 2 — Copying, Moving and Smart Pointers

A function builds a vector of a million readings and returns it. In C the question would not arise: a function returns a pointer and the caller frees the block. In C++ the vector is an object returned by value, and an object returned by value is, in principle, a copy. The program below counts. Its element type `Tracked` (shown in [Section 2.3](#sec-2-3)) adds one to a global counter each time one of its values is copied or moved.

```cpp
const Tracked *seen = nullptr;          // where the elements lived inside the function

std::vector<Tracked> make_readings(int n)
{
    std::vector<Tracked> v;
    v.reserve(n);
    for (int i = 0; i < n; i++)
        v.emplace_back(i);              // built in place: no copy, no move
    seen = v.data();
    return v;
}

int main()
{
    std::vector<Tracked> r = make_readings(1000000);
    std::printf("returned:  %ld copies, %ld moves, same elements: %s\n",
                counts.copies, counts.moves, r.data() == seen ? "yes" : "no");
    std::vector<Tracked> backup = r;    // now ask for a copy
    std::printf("backup:    %ld copies, %ld moves\n", counts.copies, counts.moves);
    return 0;
}
```

***Listing 2.1.** A million values returned by value code/bachelor-2/02-cpp-copy-move/listings/hook.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o hook hook.cpp && ./hook
returned:  0 copies, 0 moves, same elements: yes
backup:    1000000 copies, 0 moves
```

***Output 2.1.** Returning copied nothing; asking for a copy copied a million values.*

Returning the vector copied nothing and moved nothing: the elements the caller holds are the very ones the function built, at the same address. Writing `backup = r` copied all million. This chapter explains both lines: what a copy of an object that owns memory must do, how C++ hands over the memory instead of copying it when the source is about to die, and how the standard [smart pointers](#def-b2-cpp-copy-move-unique-ptr) express who owns a heap object.

**You already know.**

[Chapter 1](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#ch-b2-cpp-classes-raii): an object that owns a resource acquires it in its [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) and releases it in its [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) (RAII), and copying such an object was forbidden with `= delete` until this chapter. A dynamic array (Book 3) keeps $n$ elements in a block of capacity $c \geq n$; when it is full it allocates a larger block, carries the $n$ elements over and frees the old one. Doubling the capacity makes the amortised cost of an append constant.

## 2.1 Copying an object that owns memory

**Definition 2.1 (Copy constructor, copy assignment operator).**

The *copy constructor* of a class `T` is the [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) `T(const T &)`: it builds a new object from an existing one, as in `T b = a;` or when `a` is passed by value. The *copy assignment operator* `T &operator=(const T &)` gives an existing object the value of another, as in `b = a;`. If a class declares neither, the compiler writes them: they copy each member in turn.

For a class whose members are numbers and strings, the compiler’s copy is right. For a class that holds a raw pointer to a block it owns, it copies the pointer and not the block. The `Buffer` below owns a heap copy of a street name; it has a [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) and lets the compiler write its copy.

```cpp
class Buffer {
public:
    explicit Buffer(const char *text) : n_(std::strlen(text)), data_(new char[n_ + 1])
    {
        std::memcpy(data_, text, n_ + 1);
    }
    ~Buffer() { delete[] data_; }
    const char *c_str() const { return data_; }

private:
    std::size_t n_;
    char *data_;
};

int main()
{
    Buffer a("Harbour Road");
    Buffer b = a;                    // the implicit copy constructor
    std::cout << a.c_str() << " / " << b.c_str() << '\n';
    return 0;                        // b is destroyed, then a: the same block twice
}
```

***Listing 2.2.** A buffer with the compiler’s copy code/bachelor-2/02-cpp-copy-move/listings/shallow.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o shallow shallow.cpp && ./shallow
=================================================================
==1000==ERROR: AddressSanitizer: attempting double-free on 0x502000000010 in thread T0:
    #0 0x7ffff74b6e57 in operator delete[](void*) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:163
    #1 0x5555555557ff in Buffer::~Buffer() shallow.cpp:12
    #2 0x555555555570 in main shallow.cpp:26
0x502000000010 is located 0 bytes inside of 13-byte region [0x502000000010,0x50200000001d)
freed by thread T0 here:
    #0 0x7ffff74b6e57 in operator delete[](void*) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:163
    #1 0x5555555557ff in Buffer::~Buffer() shallow.cpp:12
    #2 0x555555555563 in main shallow.cpp:26
previously allocated by thread T0 here:
    #0 0x7ffff74b6357 in operator new[](unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:102
    #1 0x555555555736 in Buffer::Buffer(char const*) shallow.cpp:8
    #2 0x55555555549a in main shallow.cpp:22
SUMMARY: AddressSanitizer: double-free ../../../../src/libsanitizer/asan/asan_new_delete.cpp:163 in operator delete[](void*)
==1000==ABORTING
[exit status 1]
```

***Output 2.2.** AddressSanitizer: the same block freed twice. Some lines are left out.*

The line printed by `main` is missing: the output stream had not been flushed when the sanitizer stopped the program. The report itself is exact: the block allocated on line 22 (for `a`) was freed by a [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) called on line 26 (that of `b`, destroyed first) and then again by the next [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) (that of `a`). Without the sanitizer, freeing a block twice is undefined behaviour, which in practice corrupts the allocator’s lists and fails far from the cause.

**Definition 2.2 (Shallow copy, deep copy).**

A *shallow copy* of an object copies its pointers, so that the copy and the original share the blocks they point to. A *deep copy* allocates new blocks for the copy and copies their contents, so that the two objects share nothing and each can change or free its blocks alone.

![Two Buffer objects after Buffer b = a;. Each object holds the length of the text, 12, and a pointer to a block of 13 bytes. On the left, the compiler’s copy: both pointers name the same block. On the right, a copy constructor that allocates: each object owns its block.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-copy-move/fig-fe0311444208.svg)

*Two `Buffer` objects after `Buffer b = a;`. Each object holds the length of the text, 12, and a pointer to a block of 13 bytes. On the left, the compiler’s copy: both pointers name the same block. On the right, a [copy constructor](#def-b2-cpp-copy-move-copy) that allocates: each object owns its block.*

The fix writes the [copy constructor](#def-b2-cpp-copy-move-copy) and the copy assignment by hand. The [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) allocates a block of its own and copies the characters; the assignment is written in the form of [Section 2.2](#sec-2-2).

```cpp
class Buffer {
public:
    explicit Buffer(const char *text) : n_(std::strlen(text)), data_(new char[n_ + 1])
    {
        std::memcpy(data_, text, n_ + 1);
    }
    ~Buffer() { delete[] data_; }
    Buffer(const Buffer &o) : n_(o.n_), data_(new char[o.n_ + 1])   // a block of its own
    {
        std::memcpy(data_, o.data_, n_ + 1);
    }
    Buffer &operator=(const Buffer &o)          // copy and swap
    {
        Buffer tmp(o);                          // may throw: *this not touched yet
        std::swap(n_, tmp.n_);
        std::swap(data_, tmp.data_);
        return *this;                           // tmp dies with the old block
    }
    const char *c_str() const { return data_; }
    std::size_t size() const { return n_; }
    void upcase_first() { if (n_ > 0 && data_[0] >= 'a' && data_[0] <= 'z') data_[0] -= 32; }

private:
    std::size_t n_;
    char *data_;
};
```

***Listing 2.3.** A buffer with a [deep copy](#def-b2-cpp-copy-move-deep) code/bachelor-2/02-cpp-copy-move/listings/buffer.hpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o deep_copy deep_copy.cpp && ./deep_copy
harbour Road / Harbour Road / harbour Road
three blocks: true
```

***Output 2.3.** Three buffers, three blocks; the sanitizer is silent.*

Changing `b` left `a` alone, and the sanitizer found nothing to report. The three functions written here, the [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor), the [copy constructor](#def-b2-cpp-copy-move-copy) and the copy assignment, go together: a class that needs one of them almost always needs the three, since a [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) that frees means a raw resource that a member-wise copy would share. This is the *rule of three*, which [Section 2.4](#sec-2-4) completes.

## 2.2 Value semantics

**Definition 2.3 (Value semantics, reference semantics).**

A type has *value semantics* if a copy of an object is a new, independent object with the same value: changing one never changes the other, as with `int`, `std::string` and the `Buffer` of [Listing 2.3](#lst-b2-cpp-copy-move-buffer). A type has *reference semantics* if copying an object gives a second name for the same underlying data, as with a pointer, or with every object in Python.

The C++ standard library gives its containers [value semantics](#def-b2-cpp-copy-move-value-semantics), and a class that owns memory should do the same unless there is a reason not to. The assignment of [Listing 2.3](#lst-b2-cpp-copy-move-buffer) has a pattern of its own, named after its two steps.

**Method 2.4 (Copy and swap).**

To write `T &operator=(const T &o)` for a class that owns resources:

1. make a local copy `tmp` of `o` with the [copy constructor](#def-b2-cpp-copy-move-copy) (all the work that may fail happens here, before `*this` is touched);
2. exchange the members of `*this` and `tmp` , with operations that cannot throw ( `std::swap` of pointers and numbers);
3. return `*this` ; at the end of the function, `tmp` is destroyed and frees the old resources.

**Proposition 2.5 (Copy and swap is strong).**

An assignment written by [Method 2.4](#met-b2-cpp-copy-move-copy-and-swap) gives the strong guarantee: if it throws, the target is unchanged. It is also correct when the source and the target are the same object.

**Proof.** Only step 1 can throw, since swaps of pointers and integers cannot. If it throws, the [copy constructor](#def-b2-cpp-copy-move-copy) has cleaned up after itself (its partly built members are destroyed, [Chapter 1](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#ch-b2-cpp-classes-raii)), and no statement has yet changed `*this`: the target keeps its value. If step 1 succeeds, `tmp` holds an independent copy of the value of `o`; the swaps give that value to `*this` and the old resources to `tmp`, whose [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) frees them. When `o` is `*this`, step 1 copies the target’s own value into fresh blocks before anything is freed, so the result is again that value. ∎

The self-assignment case is not academic: `v[i] = v[j]` with $i = j$ is one, and an assignment written as “free my block, allocate a new one, copy the source’s characters” reads freed memory in that case ([Exercise 2.2](#exo-b2-cpp-copy-move-2)). The price of copy and swap is a new allocation even when the target’s block was large enough; the standard containers reuse the target’s memory when they can, and in exchange do not promise the strong guarantee for their assignment.

## 2.3 Moving

A copy is the right meaning of `b = a` when `a` is used afterwards. When the source is a temporary about to be destroyed, copying its block and then freeing the original is wasted work: the target could take the block itself. C++ tells the two cases apart by the kind of expression the source is.

**Definition 2.6 (Value category, lvalue, rvalue).**

Every expression has a *value category*. An *lvalue* names an object that outlives the expression: a variable `a`, `*p`, `v[i]`. A *prvalue* computes a value that no name holds yet: `42`, `x + y`, a call `f()` returning by value, `Buffer("Quay")`. An *xvalue* names an object whose resources may be taken, such as `std::move(a)`. Prvalues and xvalues together are the *rvalues*.

**Definition 2.7 (Rvalue reference).**

An *rvalue reference* `T &&` is a reference that binds only to [rvalues](#def-b2-cpp-copy-move-rvalue). When a function is overloaded on `const T &` and `T &&`, a call with an [lvalue](#def-b2-cpp-copy-move-rvalue) picks the first and a call with an [rvalue](#def-b2-cpp-copy-move-rvalue) picks the second. `std::move(a)` does not move anything: it is a cast of the [lvalue](#def-b2-cpp-copy-move-rvalue) `a` to an xvalue, which tells the overload resolution that `a` may be emptied.

**Definition 2.8 (Move constructor, move assignment, moved-from object).**

The *move constructor* `T(T &&o)` and the *move assignment operator* `T &operator=(T &&o)` build or assign from an [rvalue](#def-b2-cpp-copy-move-rvalue) by taking `o`’s resources rather than copying them. Afterwards `o` is a *moved-from object*: it must still be valid, which means it can be destroyed and assigned a new value, but its value is unspecified unless its class documents it.

[Rvalue references](#def-b2-cpp-copy-move-rvalue-reference) and moves arrived in C++11. The `Buffer` below has both a copy and a [move constructor](#def-b2-cpp-copy-move-move), each announcing itself; the move takes the pointer and leaves the source with none.

```cpp
    Buffer(const Buffer &o) : n_(o.n_), data_(new char[n_ + 1])
    {
        std::memcpy(data_, o.data_, n_ + 1);
        std::puts("  copy constructor");
    }
    Buffer(Buffer &&o) noexcept : n_(o.n_), data_(o.data_)     // steal the block
    {
        o.n_ = 0;
        o.data_ = nullptr;                                     // the source owns nothing
        std::puts("  move constructor");
    }
    const char *c_str() const { return data_ ? data_ : "(empty)"; }

private:
    std::size_t n_;
    char *data_;
};

Buffer label(const char *t) { return Buffer(t); }   // a prvalue: built in place

int main()
{
    Buffer a("Mill Lane");
    std::puts("Buffer b = a;");
    Buffer b = a;                       // a is an lvalue: copy
    std::puts("Buffer c = std::move(a);");
    Buffer c = std::move(a);            // std::move(a) is an xvalue: move
    std::puts("Buffer d = label(...);");
    Buffer d = label("Quay Street");    // guaranteed elision: neither
    std::printf("a=%s b=%s c=%s d=%s\n", a.c_str(), b.c_str(), c.c_str(), d.c_str());
    return 0;
}
```

***Listing 2.4.** A copy, a move and neither code/bachelor-2/02-cpp-copy-move/listings/move_demo.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o move_demo move_demo.cpp && ./move_demo
Buffer b = a;
  copy constructor
Buffer c = std::move(a);
  move constructor
Buffer d = label(...);
a=(empty) b=Mill Lane c=Mill Lane d=Quay Street
```

***Output 2.4.** The move left `a` empty.*

![A move copies the two members of a into c and then empties a, so that exactly one object owns the block. Nothing is allocated, and the cost does not depend on the length of the text.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-copy-move/fig-5894bfe8790d.svg)

*A move copies the two members of `a` into `c` and then empties `a`, so that exactly one object owns the block. Nothing is allocated, and the cost does not depend on the length of the text.*

The third statement printed no [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) at all: `label` returns the prvalue `Buffer(t)`, and C++17 requires that it be built directly in `d`.

**Definition 2.9 (Copy elision).**

*Copy elision* is the construction of an object directly in its final place, which removes a copy or move. Since C++17 it is guaranteed when an object is initialised from a prvalue of its type: `T x = T(...)`, `T x = f()` with `f` returning a prvalue, and `return T(...);`. When a function returns a named local object, the compiler may also build it in the caller’s object (the *named return value optimisation*), but is not required to; if it does not, the return moves.

This is the first line of [Output 2.1](#out-b2-cpp-copy-move-hook): `make_readings` returns its local vector `v` by name, the compiler built `v` in the caller’s `r`, and had it not done so the return would have moved the vector, which copies three pointers and touches no element. The first line counts element copies and moves, so it would read the same either way: what it shows is that no element was copied, not which of the two happened. Returning a large object by value is therefore cheap in C++, and the usual style.

**In practice — When to write std::move.**

Write `std::move(x)` only when `x` is a named object you will not read again: passing it to a function that keeps it, or pushing it into a container. Do not write `return std::move(local);`: it turns the returned name into an xvalue, which forbids the elision and forces a move. Do not move from a `const` object: `std::move` gives a `const T &&`, which binds only to the [copy constructor](#def-b2-cpp-copy-move-copy), and the “move” silently copies.

A vector that grows faces the same choice. When it carries its elements to a larger block, moving them is cheaper than copying them. But if one move throws halfway, some elements are in the new block and some, already moved from, in the old one, and the strong guarantee of `push_back` is lost. The library therefore moves only if the [move constructor](#def-b2-cpp-copy-move-move) is declared `noexcept`, and copies otherwise. `Tracked`, the type of the opening, comes in two versions that differ only in that word.

```cpp
class Tracked {                        // its move constructor promises not to throw
public:
    explicit Tracked(int v = 0) : v_(v) {}
    Tracked(const Tracked &o) : v_(o.v_) { counts.copies++; }
    Tracked(Tracked &&o) noexcept : v_(o.v_) { counts.moves++; }
    Tracked &operator=(const Tracked &o) { v_ = o.v_; counts.copies++; return *this; }
    Tracked &operator=(Tracked &&o) noexcept { v_ = o.v_; counts.moves++; return *this; }
    int value() const { return v_; }

private:
    int v_;
};

class TrackedMayThrow {                // the same, without noexcept on the moves
public:
    explicit TrackedMayThrow(int v = 0) : v_(v) {}
    TrackedMayThrow(const TrackedMayThrow &o) : v_(o.v_) { counts.copies++; }
    TrackedMayThrow(TrackedMayThrow &&o) : v_(o.v_) { counts.moves++; }
    TrackedMayThrow &operator=(const TrackedMayThrow &o)
        { v_ = o.v_; counts.copies++; return *this; }
    TrackedMayThrow &operator=(TrackedMayThrow &&o)
        { v_ = o.v_; counts.moves++; return *this; }
    int value() const { return v_; }
```

***Listing 2.5.** A value that counts its copies and moves, in two versions code/bachelor-2/02-cpp-copy-move/listings/tracked.hpp*

```cpp
template <class T> void fill(const char *name, int n)
{
    counts = Counts{};
    std::vector<T> v;
    std::size_t cap = v.capacity(), regrowths = 0;
    for (int i = 0; i < n; i++) {
        v.push_back(T(i));               // the temporary T(i) is moved in
        if (v.capacity() != cap) {
            regrowths++;
            cap = v.capacity();
        }
    }
    std::printf("%-16s n=%d: %2zu regrowths, capacity %zu, %ld copies, %ld moves\n",
                name, n, regrowths, cap, counts.copies, counts.moves);
}
```

***Listing 2.6.** Filling a vector from empty code/bachelor-2/02-cpp-copy-move/listings/growth.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o growth growth.cpp && ./growth
noexcept move    n=1000: 11 regrowths, capacity 1024, 0 copies, 2023 moves
move may throw   n=1000: 11 regrowths, capacity 1024, 1023 copies, 1000 moves
noexcept move    n=1025: 12 regrowths, capacity 2048, 0 copies, 3072 moves
move may throw   n=1025: 12 regrowths, capacity 2048, 2047 copies, 1025 moves
```

***Output 2.5.** The same pushes, moved or copied at each regrowth.*

Each push moves its temporary into the vector, hence $n$ moves in every line. With $n = 1000$ the capacity went $1, 2, 4, \dots, 1024$ in 11 regrowths, which carried $1 + 2 + \dots + 512 = 1023$ elements: 1023 more moves with `noexcept`, 1023 copies without it. The count is bounded for any growth factor.

**Proposition 2.10 (Transfers of a growing array).**

An array starts empty and receives $n \geq 2$ elements by appends. Whenever it is full, it moves to a block whose capacity is at least $r$ times the old one, for a fixed $r > 1$, and carries all its elements over. Then the total number of elements carried over is less than $\frac{r}{r-1}(n-1)$. For elements whose [move constructor](#def-b2-cpp-copy-move-move) is `noexcept`, each transfer of a `std::vector` is a move and no element is ever copied; otherwise each transfer is a copy.

**Proof.** Let $c_1 < c_2 < \dots < c_k$ be the capacities at which the array was full and regrew; regrowth $j$ carries $c_j$ elements. Since $c_{j+1} \geq r c_j$, we have $c_j \leq c_k / r^{k-j}$, and

$$
\sum_{j=1}^{k} c_j \leq c_k \sum_{i=0}^{k-1} r^{-i} < c_k \cdot \frac{1}{1 - 1/r} = \frac{r}{r-1}\, c_k .
$$

The last regrowth happened when the array already held $c_k$ elements and received another, so $c_k + 1 \leq n$, and the sum is less than $\frac{r}{r-1}(n-1)$. If there was no regrowth the sum is $0$. The last sentence is the rule of the library: it transfers with the [move constructor](#def-b2-cpp-copy-move-move) exactly when that [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) cannot throw, or when there is no [copy constructor](#def-b2-cpp-copy-move-copy). ∎

For $r = 2$ the bound is $2(n-1)$; the run made 1023 transfers for $n = 1000$, under 1998, and 2047 for $n = 1025$, under 2048. With $n$ just above a power of two the bound is nearly reached ([Exercise 2.11](#exo-b2-cpp-copy-move-11)). Added to the $n$ insertions themselves, a vector of $n$ elements is filled with fewer than $3n$ element operations, which is the amortised constant cost recalled at the start, now counted exactly.

## 2.4 The rule of zero and the rule of five

A class can declare five special members beyond its ordinary [constructors](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor): the [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor), the [copy constructor](#def-b2-cpp-copy-move-copy), the copy assignment, the [move constructor](#def-b2-cpp-copy-move-move) and the move assignment. The compiler writes the missing ones, member by member, under rules that come down to this: declaring a [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) or a copy operation stops the compiler from writing the moves (copies are used instead), and declaring a move operation deletes the copies.

**Definition 2.11 (Rule of zero, rule of five).**

The *rule of zero* says that a class whose members all manage their own resources (strings, containers, [smart pointers](#def-b2-cpp-copy-move-unique-ptr)) should declare none of the five special members: the member-wise versions the compiler writes are correct. The *rule of five* says that a class that manages a resource itself, and so declares one of the five, should declare all five, each written or explicitly `= default` or `= delete`.

**Method 2.12 (Applying the rule of zero).**

To give a class correct copies and moves:

1. hold each resource in a member of a type that already owns it: `std::string` , `std::vector` , `std::unique_ptr` , or a small class of your own written once by the [rule of five](#def-b2-cpp-copy-move-rules) ;
2. declare none of the five special members in the class itself;
3. check the result: the class copies if every member copies, and moves cheaply if every member moves cheaply.

```cpp
struct Station {                        // rule of zero: none of the five is written
    std::string name;
    std::vector<double> readings;
};

struct Sensor {                         // a move-only member makes the class move-only
    std::string id;
    std::unique_ptr<int> calibration;
};

int main()
{
    Station a{"Riverside", {18.5, 19.0}};
    Station b = a;                      // member-wise copy: a deep copy
    b.readings.push_back(21.5);
    Station c = std::move(b);           // member-wise move
    std::cout << a.readings.size() << ' ' << c.readings.size() << ' '
              << b.readings.size() << '\n';
    Sensor s{"T-4", std::make_unique<int>(12)};
    Sensor t = std::move(s);            // fine; Sensor u = t; would not compile
    std::cout << t.id << ' ' << *t.calibration << ' '
        << (s.calibration ? "full" : "empty") << '\n';
    return 0;
}
```

***Listing 2.7.** Two classes that declare nothing special code/bachelor-2/02-cpp-copy-move/listings/rule_of_zero.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o rule_of_zero rule_of_zero.cpp && ./rule_of_zero
2 3 0
T-4 12 empty
```

***Output 2.6.** The copy is deep, the moved-from vector is empty, the sensor moved.*

`Station` copies and moves correctly with no code at all, because `std::string` and `std::vector` do. `Sensor` cannot be copied, because one member cannot: a member that is move-only makes its class move-only. The moved-from `b.readings` printed 0, which is what the library’s vector leaves behind, though only its validity is promised. Of the five special members, a class following the [rule of zero](#def-b2-cpp-copy-move-rules) writes none; `Buffer`, which manages a raw block, is the kind of class that writes them all, once ([Exercise 2.3](#exo-b2-cpp-copy-move-3)).

## 2.5 Smart pointers

In C, a pointer returned by a function says nothing about who must free the block. C++ separates the two meanings of a pointer: an *owning* pointer, whose holder must free the object, and a plain pointer or reference, which only refers to an object owned by someone else. Owning pointers are objects of the standard library.

**Definition 2.13 (Smart pointer, unique pointer, unique ownership).**

A *smart pointer* is a class that holds a pointer to a heap object and releases the object in its [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor). The *unique pointer* `std::unique_ptr<T>` is the *sole* owner of its object (*unique ownership*): it cannot be copied, it can be moved, which transfers the ownership and leaves the source null, and its [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) deletes the object if it holds one. `std::make_unique<T>(args)` allocates and constructs the object.

```cpp
struct Photo {
    std::string name;
    explicit Photo(std::string n) : name(std::move(n))
        { std::printf("  load %s\n", name.c_str()); }
    ~Photo() { std::printf("  free %s\n", name.c_str()); }
};

std::unique_ptr<Photo> open_photo(const char *name)
{
    return std::make_unique<Photo>(name);        // ownership leaves the function
}

int main()
{
    std::vector<std::unique_ptr<Photo>> album;
    album.push_back(open_photo("pier.jpg"));
    auto p = open_photo("dunes.jpg");
    album.push_back(std::move(p));               // album.push_back(p) does not compile
    std::printf("p is %s, album holds %zu\n", p ? "full" : "empty", album.size());
    album.erase(album.begin());                  // the photo goes with its owner
    std::puts("end of main");
    return 0;
}
```

***Listing 2.8.** Photos owned by an album code/bachelor-2/02-cpp-copy-move/listings/unique.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o unique unique.cpp && ./unique
  load pier.jpg
  load dunes.jpg
p is empty, album holds 2
  free pier.jpg
end of main
  free dunes.jpg
```

***Output 2.7.** Each photo is freed when its owner goes.*

A `std::unique_ptr` holds one pointer and nothing else, so it costs what a raw pointer costs. The rule that follows is short: `new` and `delete` no longer appear in application code. Sometimes, though, an object has several owners and none of them knows which will finish last: a photo shown in two albums, a cached page held by several requests.

**Definition 2.14 (Shared pointer, shared ownership, weak pointer).**

A *shared pointer* `std::shared_ptr<T>` is one of possibly several owners of an object (*shared ownership*). The object comes with a *control block* that counts its shared pointers: copying a `shared_ptr` adds one, destroying or resetting one subtracts one, and the owner that brings the count to zero deletes the object. A *weak pointer* `std::weak_ptr<T>` refers to an object owned by shared pointers without being counted as an owner; `lock()` gives a `shared_ptr` to the object if it is still alive, and a null one if not.

The count makes a [shared pointer](#def-b2-cpp-copy-move-shared-ptr) cost more than a unique one (a second block, and an update of the count on every copy), and it has a blind spot. In the program below a photo owns its album and the album owns its cover photo.

```cpp
struct Album;
struct Photo {
    std::string name;
    std::shared_ptr<Album> album;               // a photo keeps its album alive
    ~Photo() { std::printf("free photo %s\n", name.c_str()); }
};
struct Album {
    std::string title;
    std::shared_ptr<Photo> cover;               // an album keeps its cover alive
    ~Album() { std::printf("free album %s\n", title.c_str()); }
};

int main()
{
    auto a = std::make_shared<Album>();
    a->title = "Coast";
    auto p = std::make_shared<Photo>();
    p->name = "pier.jpg";
    p->album = a;
    a->cover = p;
    std::printf("counts: album %ld, photo %ld\n", a.use_count(), p.use_count());
    std::fflush(stdout);                        // the leak report ends the program at once
    return 0;                                   // a and p die; the counts drop to 1
}
```

***Listing 2.9.** An album and a photo that own each other code/bachelor-2/02-cpp-copy-move/listings/shared_cycle.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o shared_cycle shared_cycle.cpp && ./shared_cycle
counts: album 2, photo 2

=================================================================
==1000==ERROR: LeakSanitizer: detected memory leaks

Indirect leak of 64 byte(s) in 1 object(s) allocated from:
    #0 0x7ffff74b61e7 in operator new(unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:99
    #10 0x5555555576a4 in main shared_cycle.cpp:23
    #11 0x7ffff6c29d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f)

Indirect leak of 64 byte(s) in 1 object(s) allocated from:
    #0 0x7ffff74b61e7 in operator new(unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:99
    #10 0x555555557655 in main shared_cycle.cpp:21
    #11 0x7ffff6c29d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f)

SUMMARY: AddressSanitizer: 128 byte(s) leaked in 2 allocation(s).
[exit status 1]
```

***Output 2.8.** LeakSanitizer reports two blocks nobody can reach. Some lines are left out.*

Neither [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) printed. When `main` returned, `a` and `p` were destroyed and each count fell from 2 to 1, the one held by the other object. Nothing outside the pair points to it any more, but each keeps the other above zero: the count only sees owners, not whether they are reachable. The fix is to decide that one direction of the edge observes rather than owns. A photo needs to know its album, but does not keep it alive.

```cpp
struct Album;
struct Photo {
    std::string name;
    std::weak_ptr<Album> album;                 // does not keep the album alive
    ~Photo() { std::printf("free photo %s\n", name.c_str()); }
};
struct Album {
    std::string title;
    std::shared_ptr<Photo> cover;
    ~Album() { std::printf("free album %s\n", title.c_str()); }
};

int main()
{
    auto p = std::make_shared<Photo>();
    p->name = "pier.jpg";
    {
        auto a = std::make_shared<Album>();
        a->title = "Coast";
        p->album = a;
        a->cover = p;
        if (auto alb = p->album.lock())         // a shared_ptr while we use it
            std::printf("pier.jpg is in %s (album count %ld)\n",
                alb->title.c_str(), a.use_count());
    }
    std::printf("album gone: %s\n", p->album.expired() ? "yes" : "no");
    return 0;
}
```

***Listing 2.10.** The photo observes its album code/bachelor-2/02-cpp-copy-move/listings/weak_fix.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o weak_fix weak_fix.cpp && ./weak_fix
pier.jpg is in Coast (album count 2)
free album Coast
album gone: yes
free photo pier.jpg
```

***Output 2.9.** Both objects freed; the photo saw its album go.*

![Each object made by make_shared carries a control block counting its strong owners and its weak observers. Left: the cycle of once a and p are gone. Right: inside the block of , while a and p still exist; the dashed edge does not count, so the album dies with a.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-copy-move/fig-c1ba03f7070d.svg)

*Each object made by `make_shared` carries a control block counting its strong owners and its weak observers. Left: the cycle of [Listing 2.9](#lst-b2-cpp-copy-move-shared-cycle) once `a` and `p` are gone. Right: inside the block of [Listing 2.10](#lst-b2-cpp-copy-move-weak-fix), while `a` and `p` still exist; the dashed edge does not count, so the album dies with `a`.*

**In practice — Choosing an owner.**

Most objects should have exactly one owner, and `std::unique_ptr` or a plain member says so. Reach for `std::shared_ptr` only when the lifetime is genuinely shared, and then draw the ownership graph: every cycle in it must contain a weak edge. Pointers back to a parent, to an observer, or to a cache entry are the usual candidates. A child owned by its parent can even point back with a raw pointer, since the parent always outlives it ([Exercise 2.9](#exo-b2-cpp-copy-move-9)). Book 5 returns to reference counting as a technique for managing memory, and to its alternatives.

Moving costs a few pointer copies whatever the size of the object; copying costs time proportional to the data. The program below measures both for vectors of `double` of growing length.

```cpp
int main()
{
    std::printf("%10s %14s %12s\n", "n", "copy (ns)", "move (ns)");
    for (int n = 1000; n <= 10000000; n *= 10) {
        std::vector<double> src(n, 1.5), dst;
        int reps = n >= 1000000 ? 20 : 2000;
        double c = ns([&] { dst = src; }, reps);   // dst already has room after the first copy
        std::vector<double>().swap(dst);                   // free dst before timing the moves
        double m = ns([&] { dst = std::move(src); src = std::move(dst); }, reps) / 2;
        std::printf("%10d %14.0f %12.1f\n", n, c, m);
    }
    return 0;
}
```

***Listing 2.11.** Copy and move of a vector, timed (`ns` returns the mean time of `reps` calls of its argument) code/bachelor-2/02-cpp-copy-move/listings/copy_vs_move.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o copy_vs_move copy_vs_move.cpp && ./copy_vs_move
         n      copy (ns)    move (ns)
      1000             39          0.2
     10000           1388          0.2
    100000          14065          0.2
   1000000         387601          1.1
  10000000        4900761          1.6
```

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

The copy grows with $n$: from a few hundredths to about a tenth of a nanosecond per element while the vectors fit in the processor’s caches, and about half a nanosecond once they do not ([Chapter 12](https://one-course.com/books/computer-science/4/en/chapter/12-caches-and-the-memory-hierarchy#ch-b2-caches)). The move stays below two nanoseconds whatever the length, because it copies three pointers and empties the source.

## 2.6 Exercises

**Exercise 2.1 ★.**

Using `Tracked` from [Listing 2.5](#lst-b2-cpp-copy-move-tracked), say for each of the lines A to F whether it copies, moves, or neither, and give the two numbers the program prints.

```cpp
Tracked pass(Tracked t) { return t; }

int main()
{
    Tracked a(1);
    Tracked b = a;                              // line A
    Tracked c = std::move(a);                   // line B
    b = c;                                      // line C
    Tracked d = pass(b);                        // line D
    std::vector<Tracked> v;
    v.reserve(4);
    v.push_back(d);                             // line E
    v.push_back(Tracked(5));                    // line F
    std::printf("%ld copies, %ld moves\n", counts.copies, counts.moves);
    return 0;
}
```

***Listing 2.12.** Copies and moves, line by line code/bachelor-2/02-cpp-copy-move/listings/exo_count.cpp*

**Solution of Exercise 2.1.**

A: `a` is an [lvalue](#def-b2-cpp-copy-move-rvalue), copy. B: `std::move(a)` is an xvalue, move. C: assignment from the [lvalue](#def-b2-cpp-copy-move-rvalue) `c`, copy assignment. D: the [lvalue](#def-b2-cpp-copy-move-rvalue) `b` initialises the parameter `t` by copy; `return t;` cannot be elided (a parameter is not built in the return slot) and moves. E: the [lvalue](#def-b2-cpp-copy-move-rvalue) `d` is copied into the vector. F: the prvalue `Tracked(5)` binds to `push_back(T &&)` and is moved in; thanks to `reserve(4)` no regrowth carries anything. Total: copies A, C, D, E and moves B, D, F.

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_count exo_count.cpp && ./exo_count
4 copies, 3 moves
```

***Output 2.14.** Four copies, three moves.*

**Exercise 2.2 ★.**

The class `Text` below has a copy assignment written the obvious way. The program assigns an object to itself. Run under AddressSanitizer, it stops at once. Explain the report, then fix the assignment twice: with a test for self-assignment, and with [Method 2.4](#met-b2-cpp-copy-move-copy-and-swap). Which fix also gives the strong guarantee?

```cpp
class Text {
public:
    explicit Text(const char *s) : data_(new char[std::strlen(s) + 1])
        { std::strcpy(data_, s); }
    ~Text() { delete[] data_; }
    Text(const Text &o) : data_(new char[std::strlen(o.data_) + 1])
        { std::strcpy(data_, o.data_); }
    Text &operator=(const Text &o)
    {
        delete[] data_;                                  // free the old text
        data_ = new char[std::strlen(o.data_) + 1];      // take room for the new one
        std::strcpy(data_, o.data_);
        return *this;
    }
    const char *c_str() const { return data_; }

private:
    char *data_;
};

int main()
{
    Text t("Old Harbour");
    Text &alias = t;
    t = alias;
    std::puts(t.c_str());
    return 0;
}
```

***Listing 2.13.** An assignment to oneself code/bachelor-2/02-cpp-copy-move/listings/exo_selfassign.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address exo_selfassign.cpp -o exo_selfassign
$ ./exo_selfassign
=================================================================
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010 at pc 0x7ffff743daa7 bp 0x7fffffffebd0 sp 0x7fffffffe378
READ of size 2 at 0x502000000010 thread T0
    #0 0x7ffff743daa6 in __interceptor_strlen ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:389
    #1 0x5555555555f7 in Text::operator=(Text const&) ~/session/exo_selfassign.cpp:15
    #2 0x5555555553cc in main ~/session/exo_selfassign.cpp:29
```

***Output 2.11.** The beginning of the report. Some lines are left out.*

**Solution of Exercise 2.2.**

`o` is `*this`, so `delete[] data_` frees the very text that `strlen(o.data_)` then reads: the report says so, a read of freed memory inside `Text::operator=` on line 15, called from line 29. First fix: begin with `if (this == &o) return *this;`. It cures self-assignment, but if `new` then throws, `data_` still holds the freed pointer and the [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) will free it again: the operation does not even give the [basic guarantee](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-guarantee). Second fix, by [Method 2.4](#met-b2-cpp-copy-move-copy-and-swap): `Text tmp(o); std::swap(data_, tmp.data_); return *this;`. The copy is made before anything is freed, so self-assignment works without a test, and by [Proposition 2.5](#prop-b2-cpp-copy-move-copy-and-swap) a throwing `new` leaves the target unchanged: only this fix is strong.

**Exercise 2.3 ★.**

Complete the `Buffer` of [Listing 2.3](#lst-b2-cpp-copy-move-buffer) by the [rule of five](#def-b2-cpp-copy-move-rules): add a `noexcept` [move constructor](#def-b2-cpp-copy-move-move) that leaves the source empty, and replace the copy assignment by a single assignment `operator=(Buffer o)` that takes its parameter by value. Explain why this one function serves as both copy and move assignment.

**Solution of Exercise 2.3.**

```cpp
class Buffer {
public:
    explicit Buffer(const char *text) : n_(std::strlen(text)), data_(new char[n_ + 1])
    {
        std::memcpy(data_, text, n_ + 1);
    }
    ~Buffer() { delete[] data_; }
    Buffer(const Buffer &o) : n_(o.n_), data_(new char[o.n_ + 1])
    {
        std::memcpy(data_, o.data_, n_ + 1);
    }
    Buffer(Buffer &&o) noexcept : n_(std::exchange(o.n_, 0)),
        data_(std::exchange(o.data_, nullptr)) {}
    Buffer &operator=(Buffer o) noexcept  // by value: copied or moved by the caller's argument
    {
        std::swap(n_, o.n_);
        std::swap(data_, o.data_);
        return *this;                         // o dies with the old block
    }
    const char *c_str() const { return data_ ? data_ : ""; }
    std::size_t size() const { return n_; }

private:
    std::size_t n_;
    char *data_;
};
```

*`Buffer` by the [rule of five](#def-b2-cpp-copy-move-rules) code/bachelor-2/02-cpp-copy-move/exercises/buffer5.hpp*

`std::exchange(x, v)` sets `x` to `v` and returns its old value, which writes “take and empty” in one expression. The parameter `o` of `operator=` is a new object built by the caller: by the [copy constructor](#def-b2-cpp-copy-move-copy) if the argument is an [lvalue](#def-b2-cpp-copy-move-rvalue), by the [move constructor](#def-b2-cpp-copy-move-move) (or directly, by elision) if it is an [rvalue](#def-b2-cpp-copy-move-rvalue). Either way the body only swaps, and `o` takes the old block away with it. One function therefore provides both assignments; the price is a [move constructor](#def-b2-cpp-copy-move-move) call more than a dedicated move assignment would make. Tested in `tests/buffer_test.cpp`.

**Exercise 2.4 ★.**

A vector doubles its capacity from 1 whenever it is full. Count exactly the elements carried over while it receives $n = 2^m$ elements, then $n = 2^m + 1$. Check both against [Proposition 2.10](#prop-b2-cpp-copy-move-growth-moves) and against [Output 2.5](#out-b2-cpp-copy-move-growth).

**Solution of Exercise 2.4.**

With $n = 2^m$ elements, the regrowths happen when the array is full at capacities $1, 2, 4, \dots, 2^{m-1}$, which carry $2^m - 1 = n - 1$ elements. With $n = 2^m + 1$ there is one more regrowth, at $2^m$, and the total is $2^{m+1} - 1 = 2n - 3$. Both are less than $2(n-1)$, the bound of [Proposition 2.10](#prop-b2-cpp-copy-move-growth-moves) for $r = 2$. The run: $n = 1000$ lies between $2^9 + 1$ and $2^{10}$, so the regrowths are those of $2^{10}$, 1023 transfers; $n = 1025 = 2^{10} + 1$ gives $2 \cdot 1025 - 3 = 2047$. Both match [Output 2.5](#out-b2-cpp-copy-move-growth).

**Exercise 2.5 ★★.**

For each of the eight numbered statements, say which special member of `W` runs, or that none does, and which rule of the chapter decides it. One of the eight depends on the compiler: which one, and what may another compiler print?

```cpp

struct W {
    W() { std::puts("default"); }
    W(const W &) { std::puts("copy constructor"); }
    W(W &&) noexcept { std::puts("move constructor"); }
    W &operator=(const W &) { std::puts("copy assignment"); return *this; }
    W &operator=(W &&) noexcept { std::puts("move assignment"); return *this; }
};

W make() { return W(); }
W named() { W w; return w; }

int main()
{
    W a;                         // 1
    W b(a);                      // 2
    W c = std::move(b);          // 3
    a = c;                       // 4
    a = make();                  // 5
    [[maybe_unused]] W d = make();   // 6
    [[maybe_unused]] W e = named();  // 7
    const W f;
    [[maybe_unused]] W g = std::move(f);   // 8
    return 0;
}
```

***Listing 2.14.** Eight statements code/bachelor-2/02-cpp-copy-move/listings/exo_which.cpp*

**Solution of Exercise 2.5.**

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_which exo_which.cpp && ./exo_which
default
copy constructor
move constructor
copy assignment
default
move assignment
default
default
default
copy constructor
```

***Output 2.15.** The ten lines.*

1: default [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor). 2: `a` is an [lvalue](#def-b2-cpp-copy-move-rvalue), [copy constructor](#def-b2-cpp-copy-move-copy). 3: an xvalue, [move constructor](#def-b2-cpp-copy-move-move). 4: assignment from an [lvalue](#def-b2-cpp-copy-move-rvalue), copy assignment. 5: `make()` builds its `W()` (`default`) in a temporary, by guaranteed elision, and the temporary, an [rvalue](#def-b2-cpp-copy-move-rvalue), is move-assigned to `a`. 6: guaranteed elision builds the result of `make` directly in `d`: `default` only. 7: `named` returns a named local; this compiler applied the named return value optimisation, so only `default` is printed. That is the statement that depends on the compiler: without the optimisation it prints `default` then `move constructor`. 8: `f` is built (`default`); `std::move(f)` has type `const W &&`, which cannot bind to `W &&` but binds to `const W &`: the [copy constructor](#def-b2-cpp-copy-move-copy) runs.

**Exercise 2.6 ★★.**

The program below should keep, for each day, the day’s list of jobs. Explain the output. Is it undefined behaviour? Fix the loop so that each day starts from the same three jobs, and say which line of the fix copies.

```cpp

int main()
{
    std::vector<std::string> jobs = {"backup", "rotate logs", "send report"};
    std::vector<std::vector<std::string>> history;
    for (int day = 1; day <= 3; day++) {
        history.push_back(std::move(jobs));            // keep today's list
        std::cout << "day " << day << ": " << jobs.size() << " jobs\n";
    }
    std::cout << "history: " << history[0].size() << ' ' << history[1].size() << ' '
              << history[2].size() << '\n';
    return 0;
}
```

***Listing 2.15.** A job list kept each day code/bachelor-2/02-cpp-copy-move/listings/exo_after_move.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_after_move exo_after_move.cpp && ./exo_after_move
day 1: 0 jobs
day 2: 0 jobs
day 3: 0 jobs
history: 3 0 0
```

***Output 2.12.** The output.*

**Solution of Exercise 2.6.**

The first `push_back(std::move(jobs))` move-constructs the day’s list in `history`, and a vector’s [move constructor](#def-b2-cpp-copy-move-move) leaves its source empty; from day 2 on, the empty `jobs` is moved, which gives empty lists. This is not undefined behaviour: a moved-from vector is valid, and calling `size` on it is allowed; the program does exactly what it says. The fix keeps `jobs` and copies it: `history.push_back(jobs);`, which is the line that copies (the three strings are copied, three times in all). If `jobs` is not needed after the loop, the last day may still move it.

**Exercise 2.7 ★★.**

Write a class template `UniquePtr<T>` with the behaviour of [Definition 2.13](#def-b2-cpp-copy-move-unique-ptr): a [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) from `T *`, no copies, a `noexcept` [move constructor](#def-b2-cpp-copy-move-move) and move assignment (a self-move must not delete the object), `*`, `->`, `get`, `release`, `reset` and a test for null. Test that a vector of a hundred `UniquePtr` frees each object exactly once.

**Solution of Exercise 2.7.**

```cpp
template <class T> class UniquePtr {
public:
    UniquePtr() noexcept = default;
    explicit UniquePtr(T *p) noexcept : p_(p) {}
    ~UniquePtr() { delete p_; }
    UniquePtr(const UniquePtr &) = delete;
    UniquePtr &operator=(const UniquePtr &) = delete;
    UniquePtr(UniquePtr &&o) noexcept : p_(std::exchange(o.p_, nullptr)) {}
    UniquePtr &operator=(UniquePtr &&o) noexcept
    {
        if (this != &o)
            reset(std::exchange(o.p_, nullptr));
        return *this;
    }
    T &operator*() const { return *p_; }
    T *operator->() const noexcept { return p_; }
    T *get() const noexcept { return p_; }
    explicit operator bool() const noexcept { return p_ != nullptr; }
    T *release() noexcept { return std::exchange(p_, nullptr); }
    void reset(T *p = nullptr) noexcept
    {
        T *old = std::exchange(p_, p);        // set first: old's destructor may look at us
        delete old;
    }

private:
    T *p_ = nullptr;
};
```

*`UniquePtr` code/bachelor-2/02-cpp-copy-move/exercises/unique_ptr.hpp*

The move assignment tests `this != &o`. With `reset` written as above, a self-move would be a no-op even without the test: the pointer is taken, which leaves `p_` null, then put back, and the old `p_` deleted is null, so nothing is deleted. The test only saves the two exchanges; it is needed with a `reset` that deletes the old pointer before storing the new one. The order “store the new pointer, then delete the old” also keeps the class correct when the deleted object’s [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) reaches back to its owner. `tests/exercises_test.cpp` counts live objects: a hundred `UniquePtr` pushed into a vector, which moves them at each regrowth, are freed exactly once each when the vector goes, and a moved-from pointer is null.

**Exercise 2.8 ★★.**

Prove [Proposition 2.5](#prop-b2-cpp-copy-move-copy-and-swap) again in the form of [Exercise 2.3](#exo-b2-cpp-copy-move-3), where the parameter is taken by value. Where does the copy that may throw now happen, and why is the target still unchanged if it throws? Does the move assignment that this function also provides give the strong guarantee?

**Solution of Exercise 2.8.**

With `Buffer &operator=(Buffer o) noexcept`, the copy that may throw is the initialisation of the parameter `o`, which happens at the call, before the body of `operator=` starts. If it throws, `operator=` is never entered and no statement has touched the target: it keeps its value, which is the strong guarantee. If it succeeds, the body only swaps pointers and numbers, which cannot throw, and the [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) of `o` frees the old block, which does not throw either. For an [rvalue](#def-b2-cpp-copy-move-rvalue) argument, `o` is built by the `noexcept` [move constructor](#def-b2-cpp-copy-move-move), so the whole assignment cannot throw: it gives the no-throw guarantee, which implies the strong one. Self-assignment works as before, since `o` is a separate copy.

**Exercise 2.9 ★★.**

Represent a tree of named places (town, quarters, buildings) with nodes that own their children through `std::vector<std::unique_ptr<Node>>` and point to their parent with a raw `Node *`. Write `add`, `path` (`town/west/mill`) and `move_child(i, to)`, which moves a whole subtree under another node. Why is a raw parent pointer safe here, and why would a `std::shared_ptr` to the parent leak? Does the moved subtree change address?

**Solution of Exercise 2.9.**

```cpp
struct Node {
    std::string name;
    Node *parent = nullptr;                          // observes; never deletes
    std::vector<std::unique_ptr<Node>> children;     // owns

    explicit Node(std::string n) : name(std::move(n)) {}
    Node &add(std::string n)
    {
        children.push_back(std::make_unique<Node>(std::move(n)));
        children.back()->parent = this;
        return *children.back();
    }
    std::string path() const
    {
        return parent ? parent->path() + "/" + name : name;
    }
    // Moves the subtree rooted at child i under the node `to` (not inside that subtree).
    void move_child(std::size_t i, Node &to)
    {
        std::unique_ptr<Node> c = std::move(children[i]);
        children.erase(children.begin() + i);
        c->parent = &to;
        to.children.push_back(std::move(c));
    }
};
```

*A tree that owns downward and observes upward code/bachelor-2/02-cpp-copy-move/exercises/tree.hpp*

A node is owned by the vector of its parent, so it is destroyed no later than its parent: whenever a node exists, its parent exists, and the raw pointer never dangles; `move_child` keeps this true by updating it. Had each child held a `std::shared_ptr` to its parent, with the parent holding its children by `shared_ptr`, each parent–child pair would be a cycle of owners and the whole tree would leak, as in [Output 2.8](#out-b2-cpp-copy-move-shared-cycle). The moved subtree keeps its address: only the `unique_ptr` that owns it moves from one vector to the other, and the test checks that `&mill` is unchanged.

**Exercise 2.10 ★★★.**

Write a string class `SmallString` that keeps strings of at most 15 characters inside the object, in a member array, and longer ones in a heap block (a *small-buffer optimisation*). Give it the five special members. What must the [move constructor](#def-b2-cpp-copy-move-move) do when the source is small, and why is it then not cheaper than a copy? Test copies and moves between every combination of small and long strings, self-assignment, and growth of a vector of them.

**Solution of Exercise 2.10.**

```cpp
    SmallString(const char *s = "") { init(s, std::strlen(s)); }
    ~SmallString() { if (!is_small()) delete[] ptr_; }
    SmallString(const SmallString &o) { init(o.ptr_, o.n_); }
    SmallString(SmallString &&o) noexcept { take(o); }
    SmallString &operator=(const SmallString &o)
    {
        if (this != &o) {
            SmallString tmp(o);                        // may throw; *this untouched
            *this = std::move(tmp);
        }
        return *this;
    }
    SmallString &operator=(SmallString &&o) noexcept
    {
        if (this != &o) {
            if (!is_small())
                delete[] ptr_;                         // free our block, then take o's state
            take(o);
        }
        return *this;
    }
    const char *c_str() const { return ptr_; }
    std::size_t size() const { return n_; }
    bool is_small() const { return ptr_ == buf_; }
    void take(SmallString &o) noexcept                 // o is left empty and small
    {
        n_ = o.n_;
        if (o.is_small()) {
            std::memcpy(buf_, o.buf_, n_ + 1);         // nothing to steal: copy the few bytes
            ptr_ = buf_;
        } else {
            ptr_ = std::exchange(o.ptr_, o.buf_);      // steal the block
        }
        o.n_ = 0;
        o.buf_[0] = '\0';
    }
```

*`SmallString` code/bachelor-2/02-cpp-copy-move/exercises/small_string.hpp*

A small string’s pointer points into the object’s own array `buf_`. Stealing it would leave the target pointing into the source, which is about to die; the [move constructor](#def-b2-cpp-copy-move-move) must copy the characters into its own array and point to that. So moving a small string costs what copying it costs, at most 16 bytes, while moving a long one takes its block. The move assignment frees the target’s block, if it has one, and then takes the source’s state with `take`, the helper the [move constructor](#def-b2-cpp-copy-move-move) also uses: nothing in it can throw. Destroying the target and rebuilding it in place with placement `new` would also work here, but it is a fragile habit, wrong as soon as the class is used as a base. `tests/exercises_test.cpp` covers copies and moves between small and long strings, self-assignment and self-move, and a vector of fifty strings that grows by moving them.

**Exercise 2.11 ★★★.**

(a) Show that the bound of [Proposition 2.10](#prop-b2-cpp-copy-move-growth-moves) cannot be improved to $\frac{r}{r-1}(n-1)
\cdot \alpha$ for any $\alpha < 1$: exhibit, for $r = 2$, values of $n$ for which the number of transfers divided by $2(n-1)$ tends to $1$. (b) What does the proof give for $r = 1.5$, and how many transfers does a growth from 1 by the factor 1.5 rounded down, but by at least one place (capacities $1, 2, 3, 4, 6, 9, \dots$), make up to $n = 100$? (c) An array that grows by a fixed number $d$ of places instead of a factor makes how many transfers for $n$ elements? Conclude about the amortised cost.

**Solution of Exercise 2.11.**

(a) For $r = 2$ and $n = 2^m + 1$, [Exercise 2.4](#exo-b2-cpp-copy-move-4) found $2n - 3$ transfers, and $(2n-3)/(2n-2) \to 1$ as $m \to \infty$: no constant $\alpha < 1$ can multiply the bound. (b) The proof gives $3(n-1)$ transfers for any growth by a factor at least $1.5$. The rounded rule does not satisfy that hypothesis ($3 \to 4$ is a factor $1.33$, $9 \to 13$ is $1.44$), so the proposition does not apply as stated; counting directly, the array is full and regrows at $1, 2, 3, 4, 6, 9, 13, 19, 28, 42, 63, 94$, which carry 284 elements for $n = 100$, still under $3 \cdot 99 = 297$. (c) With capacities $d, 2d, 3d, \dots$, the regrowths up to $n$ carry $d + 2d + \dots
+ kd = d\,k(k+1)/2$ elements with $k = \lfloor (n-1)/d \rfloor$, about $n^2/(2d)$: quadratic in $n$, so the amortised cost of an append grows like $n/(2d)$ instead of staying constant. Only a multiplicative growth gives constant amortised cost.

**Exercise 2.12 ★★★.**

A station keeps the displays that show its readings, and each display keeps its station. Explain the output, draw the ownership graph with the counts at the end of `main`, and fix the program with one `std::weak_ptr`. Which edge should it be, and why not the other? Prove that, in your fixed version, every object is freed when the last outside `shared_ptr` to the station goes, for any number of displays.

```cpp
#include <vector>

struct Display;
struct Station {
    std::string name;
    std::vector<std::shared_ptr<Display>> watchers;     // to notify on each reading
    ~Station() { std::printf("free station %s\n", name.c_str()); }
};
struct Display {
    std::string room;
    std::shared_ptr<Station> source;                   // the station shown
    ~Display() { std::printf("free display %s\n", room.c_str()); }
};

void watch(const std::shared_ptr<Station> &s, const std::string &room)
{
    auto d = std::make_shared<Display>();
    d->room = room;
    d->source = s;
    s->watchers.push_back(d);
}

int main()
{
    auto s = std::make_shared<Station>();
    s->name = "Riverside";
    watch(s, "hall");
    watch(s, "office");
    std::printf("station count %ld\n", s.use_count());
    std::fflush(stdout);
    return 0;
}
```

***Listing 2.16.** A station and its displays code/bachelor-2/02-cpp-copy-move/listings/exo_observers.cpp*

```
$ g++ -std=c++20 -O0 -g -fsanitize=address -o exo_observers exo_observers.cpp && ./exo_observers
station count 3

=================================================================
==1000==ERROR: LeakSanitizer: detected memory leaks
SUMMARY: AddressSanitizer: 232 byte(s) leaked in 4 allocation(s).
[exit status 1]
```

***Output 2.13.** The start and the end of the report. Some lines are left out.*

**Solution of Exercise 2.12.**

`station count 3`: `s` and the `source` of each display. When `main` returns, `s` goes and the station’s count falls to 2; each display is owned once, by the station’s vector. The three objects own each other in two cycles (station and hall, station and office), nothing outside reaches them, and LeakSanitizer reports four blocks: the three objects, each with its control block, and the station’s vector of two pointers. The fix makes `Display::source` a `std::weak_ptr<Station>`. The other edge cannot be the weak one: the station’s vector is the only owner of each display, so with weak edges there the displays would die as soon as `watch` returned.

```cpp
struct Station {
    std::string name;
    std::vector<std::shared_ptr<Display>> watchers;    // owns its displays
    Station() { alive++; }
    ~Station() { alive--; }
};
struct Display {
    std::string room;
    std::weak_ptr<Station> source;                     // observes: the fix
    Display() { alive++; }
    ~Display() { alive--; }
};

inline void watch(const std::shared_ptr<Station> &s, const std::string &room)
{
    auto d = std::make_shared<Display>();
    d->room = room;
    d->source = s;
    s->watchers.push_back(d);
}
```

*The fixed classes (they also count the live objects) code/bachelor-2/02-cpp-copy-move/exercises/observers_fixed.hpp*

Proof that everything is freed. In the fixed version the station’s strong count counts only [shared pointers](#def-b2-cpp-copy-move-shared-ptr) held outside the station and its displays, since the displays hold weak ones. When the last of them goes the count reaches 0, so the station is destroyed; its members are destroyed, among them the vector, which destroys its [shared pointers](#def-b2-cpp-copy-move-shared-ptr) to the displays. Each display had exactly one strong owner, that vector, so each count reaches 0 and each display is destroyed; its `weak_ptr` member does not keep anything alive. This holds for any number of displays, and the test checks that the count of live objects returns to 0.

## 2.7 Problem: The photo library that copied itself

**Problem 2.1.**

Weekend problem — The photo library that copied itself

A photo library edits images of $4000 \times 3000$ pixels, one byte per pixel, held by value in an `Image` class that counts its copies and moves. It runs the same two-step edit in two styles and then files three images in an album.

```cpp
class Image {
public:
    Image(int w, int h) : w_(w), h_(h), px_(std::size_t(w) * h, 128) {}
    Image(const Image &o) : w_(o.w_), h_(o.h_), px_(o.px_) { copies++; }
    Image(Image &&o) noexcept : w_(o.w_), h_(o.h_), px_(std::move(o.px_)) { moves++; }
    Image &operator=(const Image &o) { w_ = o.w_; h_ = o.h_; px_ = o.px_; copies++; return *this; }
    Image &operator=(Image &&o) noexcept { w_ = o.w_; h_ = o.h_; px_ = std::move(o.px_); moves++; return *this; }
    void add(int d) { for (auto &p : px_) p = std::uint8_t(p + d); }
    std::size_t bytes() const { return px_.size(); }

private:
    int w_, h_;
    std::vector<std::uint8_t> px_;
};
// Version 1: parameters by const reference, results by value.
Image brighten1(const Image &im) { Image out = im; out.add(10); return out; }
Image darken1(const Image &im) { Image out = im; out.add(-5); return out; }
// Version 2: parameters by value, changed in place and returned.
Image brighten2(Image im) { im.add(10); return im; }
Image darken2(Image im) { im.add(-5); return im; }
void report(const char *what)
{
    std::printf("%-34s %ld copies, %ld moves\n", what, copies, moves);
    copies = moves = 0;
}

int main()
{
    Image photo(4000, 3000);
    Image a = darken1(brighten1(photo));            report("1: const& in, value out");
    Image b = darken2(brighten2(photo));            report("2: by value, photo kept");
    Image c = darken2(brighten2(std::move(photo))); report("2: by value, photo moved in");
    std::vector<Image> album;
    album.push_back(a);
    album.push_back(std::move(b));
    album.push_back(std::move(c));                  report("3: three pushes, no reserve");
    std::printf("each copy: %zu bytes\n", a.bytes());
    return 0;
}
```

***Listing 2.17.** An editing pipeline code/bachelor-2/02-cpp-copy-move/listings/pipeline.cpp*

**Part I — Counting copies.**

1. How many bytes does one copy of an `Image` allocate and copy?
2. In version 1, which statements copy an `Image` when `a` is computed? Predict the count of copies and moves for the first report.
3. Why does `return out;` in `brighten1` not count as a move in this run? What would it count with a compiler that does not apply the named return value optimisation?
4. In version 2, where does the one copy of the second report happen, and why must it happen if `photo` is used again?
5. Where do the two moves of the second report happen? Why is `return im;` a move and not elided?
6. Why does the result of `brighten2` reach the parameter of `darken2` with neither a copy nor a move?

**Part II — Adding moves.**

7. Predict the third report (with `std::move(photo)` ). What may the program do with `photo` afterwards?
8. Predict the fourth report: the three `push_back` calls, with the vector growing from capacity 0 as in [Output 2.5](#out-b2-cpp-copy-move-growth) .
9. How many bytes are copied in the whole run? Compare with a version where `Image` ’s [move constructor](#def-b2-cpp-copy-move-move) lacks `noexcept` .
10. Rewrite the album part with `album.reserve(3)` ; what does the fourth report become?
11. `Image` declares its five special members only to count. Which of them would the [rule of zero](#def-b2-cpp-copy-move-rules) let it drop, and what would the class then do on a copy and a move?
12. State a rule for choosing between `const Image &` and `Image` as the parameter type of an edit function, from the counts above.

**Part III — Albums and photos.**

13. The library now lets one photo belong to several albums, and an album keeps its photos with `std::vector<std::shared_ptr<Photo>>` . Why is `std::unique_ptr` no longer possible?
14. Each photo keeps the list of albums that contain it, as `std::vector<std::shared_ptr<Album>>` . Draw the ownership graph for two albums sharing one photo, with every strong count, once the library’s own pointers to the albums are gone.
15. Which objects leak? How many bytes, for photos of the size above?
16. Fix it with [weak pointers](#def-b2-cpp-copy-move-shared-ptr) . Which edges become weak, and what are the counts afterwards?
17. When an album is deleted, a photo’s list keeps an expired `weak_ptr` . Write the loop that removes the expired entries, using `expired()` or `lock()` .
18. A photo shown on screen must not disappear while it is being drawn, even if its last album is deleted at that moment by another part of the program. Which call gives the drawing code that guarantee?

**Part IV — What a copy costs.**

19. In [Output 2.10](#out-b2-cpp-copy-move-copy-vs-move) , estimate the time per element of a copy for $n = 10^3$ and for $n = 10^7$ . Why do they differ?
20. Estimate the time of one copy of an `Image` from those figures (its elements are bytes, not `double` s: state your assumption).
21. The library processes 50 000 photos a night with version 1 and then files them. Estimate the time spent in copies, and the time saved by version 2 with `std::move` .
22. Why does the move column not grow with $n$ ? Name the members a move of `std::vector` touches.
23. A vector of $n$ images grows by doubling, without `reserve` . With [Proposition 2.10](#prop-b2-cpp-copy-move-growth-moves) , bound the bytes copied if `Image` ’s moves were not `noexcept` , for $n = 1000$ .
24. State the result of the problem: the number of transfers of a growing array, and what each costs with and without `noexcept` moves.

**Solution of Problem 2.1.**

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o pipeline pipeline.cpp && ./pipeline
1: const& in, value out            2 copies, 0 moves
2: by value, photo kept            1 copies, 2 moves
2: by value, photo moved in        0 copies, 3 moves
3: three pushes, no reserve        1 copies, 5 moves
each copy: 12000000 bytes
```

***Output 2.16.** The four reports.*

**1.** $4000 \times 3000 = 12\,000\,000$ bytes, 12 MB, allocated and copied.

**2.** `Image out = im;` in `brighten1` and the same line in `darken1`: 2 copies, 0 moves.

**3.** The compiler built each `out` directly in the caller’s object (named return value optimisation). Without it each return would move: 2 copies and 2 moves.

**4.** When `photo`, an [lvalue](#def-b2-cpp-copy-move-rvalue), initialises the parameter `im` of `brighten2`. The edit changes `im`; if it shared `photo`’s pixels, `photo` would change too, and [value semantics](#def-b2-cpp-copy-move-value-semantics) forbid that.

**5.** `return im;` in `brighten2` and in `darken2`. A parameter is built by the caller before the call, in a place chosen before the return slot is known, so it cannot be built in the return slot; the language then treats the returned name as an [rvalue](#def-b2-cpp-copy-move-rvalue) and moves.

**6.** `brighten2(photo)` is a prvalue of type `Image`; it initialises the parameter of `darken2` directly (guaranteed elision).

**7.** 0 copies, 3 moves: the parameter of `brighten2` is now move-constructed. `photo` is moved-from: the program may destroy it or assign it a new value, and should not read its pixels.

**8.** First push: capacity 0 to 1, `a` copied (1 copy). Second: capacity 1 to 2, the one element moved over and `b` moved in (2 moves). Third: 2 to 4, two elements moved over and `c` moved in (3 moves). Total 1 copy and 5 moves, as printed.

**9.** Four copies in all, 48 MB. Without `noexcept`, the three transfers of regrowth become copies (the other moves are unchanged, since only the vector checks `noexcept`): seven copies, 84 MB.

**10.** No regrowth: 1 copy and 2 moves.

**11.** All five: the member-wise copy copies the pixel vector (a [deep copy](#def-b2-cpp-copy-move-deep), the same work) and the member-wise move moves it, and the compiler’s moves are `noexcept` because the vector’s are. Only the counting is lost.

**12.** If the function needs its own copy of the argument to change it, take it by value: a caller who still needs its object pays the one copy it needs, and a caller with a temporary or a `std::move` pays nothing. If the function only reads, take `const Image &`. Version 1 copies even when the caller had a temporary.

**13.** A `unique_ptr` is the sole owner, and here a photo has one owner per album, none of which knows whether it will be the last.

**14.** Album 1 $\to$ photo and album 2 $\to$ photo (strong), photo $\to$ album 1 and photo $\to$ album 2 (strong). Once the library’s pointers are gone: photo strong 2, each album strong 1.

**15.** All three objects: each has a positive count and none is reachable. At least the photo’s 12 000 000 pixel bytes, plus the three objects and their control blocks.

**16.** The edges from the photo to its albums become weak: a photo observes the albums that contain it. While the library holds the albums: each album strong 1 and weak 1, the photo strong 2. When the library drops an album, its count reaches 0 and it is freed, which drops the photo to strong 1; when the second goes, the photo is freed too.

**17.** With C++20, `std::erase_if(albums, gone);` where `gone` is the lambda `[](const std::weak_ptr<Album> &w) {return w.expired();}`; or a loop that keeps the entries for which `w.lock()` is not null.

**18.** The drawing code holds a `std::shared_ptr<Photo>` for the whole drawing, obtained by copying another or by `lock()` on a `weak_ptr`: it is then one of the owners, and the count cannot reach 0 before it lets go. (Updating the count from several threads at once is the subject of [Chapter 15](https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation#ch-b2-threads-and-synchronisation).)

**19.** About 39 ns for $10^3$ elements, a few hundredths of a nanosecond per element; about 5 ms for $10^7$, half a nanosecond per element. The small vectors stay in the caches, from which the processor copies many bytes per cycle; the large ones come from main memory, whose rate is about ten times lower.

**20.** Assuming a byte costs what it costs inside a large vector of `double`, about $0.5/8$ ns, a copy of 12 MB takes of the order of $0.75$ ms.

**21.** Version 1 makes 2 copies per photo: $50\,000 \times 2 \times 0.75$ ms, of the order of a minute and a quarter per night. Version 2 with `std::move` makes none and saves all of it.

**22.** A move of a vector reads the three pointers of the source (start, end of the elements, end of the capacity), writes them into the target, and sets the source’s to null; it never touches the elements, so its time does not depend on $n$.

**23.** With $n = 1000$ and doubling, fewer than $2 \cdot 999 = 1998$ transfers (in fact 1023); as copies of 12 MB each, at most about 24 GB copied (in fact about 12 GB). With `noexcept` moves, no pixel is copied.

**24.** *Transfers of a growing array: fewer than $\frac{r}{r-1}(n-1)$ for a growth factor $r$, that is $2(n-1)$ for doubling, and zero copies with `noexcept` moves*: each transfer then costs a few pointer copies instead of a copy of the element’s data, 12 MB per image here.
