Reference invalidated by vector growth
Review this C++ function that caches a reference into a vector.
What a strong answer looks like
Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.
0:00 of about 25 min
Mark a line and say what kind of problem it is.0 findings
1#include <vector>
2#include <string>
3
4std::string& head_of(std::vector<std::string>& v) {
5 return v.front();
6}
7
8void process(std::vector<std::string>& names) {
9 std::string& first = head_of(names);
10 for (int i = 0; i < 1000; ++i) {
11 names.push_back("appended-" + std::to_string(i));
12 }
13 // later, log the first name
14 printf("first=%s\n", first.c_str());
15}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.
Run or narrate your approach, then ask the coach.