Skip to content

Checkpoint: Safe Lookup Results

The Course
•
40 min study

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?

Predict before running C++
#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
Text
Read

return 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 a const std::string": it holds the address of a string it may read but not change.
  • &value takes the address of value, producing a pointer to it. (In a declaration such as int& r, & means reference; in an expression, it means "address of".)
  • *pointer follows the pointer to the value, and pointer->size() is shorthand for (*pointer).size().
  • nullptr is the pointer that points at nothing. Test for it with if (pointer) or pointer == nullptr before following it; following nullptr is undefined behavior.
A pointer is an optional borrow C++
#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;
}
Text
Read 4
Review
none

The 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, with nullptr meaning "not found". A pointer is used rather than a reference because a reference cannot be empty.
  • find on a const map, which returns a const_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 on push_back.

Plan before you type

  1. Write find_copy returning std::optional<std::string>, as in the predict example.
  2. Write find_borrowed returning &found->second, or nullptr at end().
  3. Take both results for ID 2, then change the map's title through find, and print both.
  4. Insert another key and print the borrow again, to show map insertion keeps it valid.
  5. Set the borrowed pointer to nullptr before 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 returned nullptr is undefined behavior. Test the pointer first.

Practice

Exercise

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:

Text
copy: Read
borrowed: Read
after edit, copy: Read
after edit, borrowed: Changed
after insert, borrowed: Changed
missing: none, nullptr
after erase, copy: Read
Your workspace C++
#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
Run the solution C++
#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;
}
Text
copy: Read
borrowed: Read
after edit, copy: Read
after edit, borrowed: Changed
after insert, borrowed: Changed
missing: none, nullptr
after erase, copy: Read

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

Was this article helpful?

Your response is saved on this device.