12.x — Chapter 12 summary and quiz
Read one box at a time. No rush.
Quick review#
- Operator overloading teaches operators like
+,==and<<to work with your types. - Moving hands over the insides of an object instead of copying.
std::moveasks for a move. - A lambda's
[ ]captures outside variables, by copy[x]or by reference[&x]. - Projects combine everything: structs, vectors, maps, files and loops.
- Threads run work side by side. Shared data needs
std::atomicor astd::mutex.
Quick check
Pick an answer. You find out right away if it is right.
Quick check #1
What does std::move(v) do?
A move transfers the contents cheaply. Don't rely on v's value afterwards.
Quick check #2
In a lambda, what does [&count] mean?
& in the capture list means "use the real variable", so changes stick.
Quick check #3
Two threads add to the same int at the same time. What's the problem called?
A data race can give wrong results. std::atomic or a std::mutex fixes it.
Quiz time
Question #1
Write operator== for this struct:
C++
struct Point{ int x {}; int y {};};C++
bool operator==(const Point& a, const Point& b){ return a.x == b.x && a.y == b.y;}Question #2
What does this print?
C++
int total { 0 };auto add { [&total](int n) { total += n; } };add(5);add(10);std::cout << total;15. total is captured by reference, so each call changes the real total.
Question #3
Add a remove <number> command to the to-do app from 12.5 — Project: a to-do list app.
Add this branch inside the loop:
C++
else if (command == "remove"){ int n {}; std::cin >> n; if (n >= 1 && n <= static_cast<int>(tasks.size())) tasks.erase(tasks.begin() + (n - 1)); else std::cout << "No task number " << n << '\n';}Tip: press ← / → to move between lessons, / to search.