Every lookup function answers a design question, whether or not its author noticed: does the caller get its own copy of the result, or a borrow of the value inside the container? A copy is independent. The caller can keep it as long as it likes, and editing it changes nothing in the tracker. A borrow, such as a pointer or reference into the map, avoids the copy and always shows the current value, but it comes with an obligation: the caller must stop using it before the element is removed.
This checkpoint builds both versions side by side so you can see exactly what each promises. The project chooses owning copies for Tracker::find, because a learner's test code can then never dangle. It borrows in one deliberate place, Task::title(), whose header comment says how long the reference stays valid.
Predict and run
lookup returns an optional copy of the title. The caller changes its copy. What does the map hold?
#include <iostream>
#include <map>
#include <optional>
#include <string>
std::optional<std::string> lookup(const std::map<int,std::string>& titles,int id) {
auto found = titles.find(id);
if (found == titles.end()) { return std::nullopt; }
return found->second;
}
int main() {
std::map<int,std::string> titles{{2,"Read"}};
auto copy = lookup(titles,2);
if (copy) { *copy = "Changed"; }
std::cout << titles.find(2)->second << "\n";
return 0;
}Check your prediction
Readreturn found->second; copies the string into the optional, so *copy = "Changed" edits the caller's copy only. If lookup returned a std::string_view instead, the caller would see the map's characters directly, and would have to stop using the view before entry 2 is erased or its title is reassigned.
Pointers: a borrow that can be empty
A reference must refer to something, so it cannot say "not found". The tool for a borrow that may be absent is a pointer. You need only four pieces of syntax:
const std::string*is the type "pointer to aconst std::string": it holds the address of a string it may read but not change.&valuetakes the address ofvalue, producing a pointer to it. (In a declaration such asint& r,&means reference; in an expression, it means "address of".)*pointerfollows the pointer to the value, andpointer->size()is shorthand for(*pointer).size().nullptris the pointer that points at nothing. Test for it withif (pointer)orpointer == nullptrbefore following it; followingnullptris undefined behavior.
#include <iostream>
#include <string>
int main() {
std::string title = "Read";
const std::string* borrowed = &title;
std::cout << *borrowed << " " << borrowed->size() << "\n";
title = "Review";
std::cout << *borrowed << "\n";
borrowed = nullptr;
std::cout << (borrowed ? "has value" : "none") << "\n";
return 0;
}Read 4
Review
noneThe second line shows the key difference from a copy: the pointer still refers to title, so it sees the new value. With a map, &found->second is the address of the value stored in the entry, found->second, so a function can return it as a borrow, or return nullptr when find reached end().
What you will use
std::optional<std::string>for an owning result that can be absent.const std::string*for a borrowed result, withnullptrmeaning "not found". A pointer is used rather than a reference because a reference cannot be empty.findon aconstmap, which returns aconst_iterator, so the borrow is read-only.- The invalidation rules of
std::map. It stores each entry in its own node, so inserting other keys never moves existing entries, and erasing a key invalidates only pointers to that entry. A vector, by contrast, can move every element onpush_back.
Plan before you type
- Write
find_copyreturningstd::optional<std::string>, as in the predict example. - Write
find_borrowedreturning&found->second, ornullptratend(). - Take both results for ID 2, then change the map's title through
find, and print both. - Insert another key and print the borrow again, to show map insertion keeps it valid.
- Set the borrowed pointer to
nullptrbefore erasing ID 2, erase it, and print the copy.
Prove it can fail
Change find_copy to borrow: give it the return type const std::string* and the same body as find_borrowed. main still compiles, because !copy and *copy work on pointers too. The "after edit, copy" line must now print Changed, because the caller no longer holds a copy, and the last line now reads an erased entry. That is a use-after-free: do not trust whatever it prints. Built natively with -fsanitize=address, the program stops on that line with a heap-use-after-free report.
Mistakes worth checking for
- An edit to a lookup result changes the tracker: the function returned a reference or pointer where a copy was intended.
- A lookup result changes when the tracker changes: the same cause, seen from the other side. Decide which behavior you want and name it.
- A crash or garbage after
erase: the code kept a pointer, reference or view into the erased entry. Clear borrows before removing what they borrow from. - A borrow into a vector breaks after an unrelated insert: vector growth relocates all elements. The map rule (insertion is safe) does not apply to vectors.
- Dereferencing the "not found" result: reading
*find_borrowed(...)when it returnednullptris undefined behavior. Test the pointer first.
Practice
Your turn
Write std::optional<std::string> find_copy(const std::map<int, std::string>&, int id) and const std::string* find_borrowed(const std::map<int, std::string>&, int id). Starting from {2, "Read"}, follow the plan and print:
copy: Read
borrowed: Read
after edit, copy: Read
after edit, borrowed: Changed
after insert, borrowed: Changed
missing: none, nullptr
after erase, copy: Read#include <iostream>
#include <map>
#include <optional>
#include <string>
// Write find_copy and find_borrowed here.
int main() {
std::map<int, std::string> titles{{2, "Read"}};
return 0;
}Hint 1: the idea
A returned owning value has an independent lifetime; a returned pointer has the lifetime of the map entry. Print both after each change and the difference becomes visible.
Hint 2: a first step
Write find_copy first and print copy: Read. Then give find_borrowed the same find call, and decide what to return in each branch: an address when the entry exists, or the empty pointer. To change the map's title in main for the edit step, assign through titles.find(2)->second, which is safe because ID 2 is known to exist at that point.
Show one solution
#include <iostream>
#include <map>
#include <optional>
#include <string>
std::optional<std::string> find_copy(const std::map<int, std::string>& titles, int id) {
auto found = titles.find(id);
if (found == titles.end()) { return std::nullopt; }
return found->second;
}
const std::string* find_borrowed(const std::map<int, std::string>& titles, int id) {
auto found = titles.find(id);
return found == titles.end() ? nullptr : &found->second;
}
int main() {
std::map<int, std::string> titles{{2, "Read"}};
const auto copy = find_copy(titles, 2);
const std::string* borrowed = find_borrowed(titles, 2);
if (!copy || !borrowed) { return 1; }
std::cout << "copy: " << *copy << "\n";
std::cout << "borrowed: " << *borrowed << "\n";
titles.find(2)->second = "Changed";
std::cout << "after edit, copy: " << *copy << "\n";
std::cout << "after edit, borrowed: " << *borrowed << "\n";
titles.emplace(5, "Review");
std::cout << "after insert, borrowed: " << *borrowed << "\n";
std::cout << "missing: " << (find_copy(titles, 9) ? "found" : "none") << ", "
<< (find_borrowed(titles, 9) ? "pointer" : "nullptr") << "\n";
borrowed = nullptr;
titles.erase(2);
std::cout << "after erase, copy: " << *copy << "\n";
return 0;
}copy: Read
borrowed: Read
after edit, copy: Read
after edit, borrowed: Changed
after insert, borrowed: Changed
missing: none, nullptr
after erase, copy: ReadThe copy kept "Read" through the edit and survived the erase, because it shares nothing with the map. The pointer followed the edit and stayed valid across the insert, because map entries do not move, and it was cleared before the only operation that could invalidate it. Both interfaces are correct; they make different promises, and the caller must know which one it has. Day 6 removes the repeated loops in reports with a function template.
Completion is saved in this browser only. It does not measure mastery.