A reference int& r = v[0]; is taken, then v.push_back(99) triggers a reallocation. What is the state of r?
Correct answer
B. It dangles, because growth allocates a new buffer and destroys the old elements
16 views
B. It dangles, because growth allocates a new buffer and destroys the old elements
16 views
Vector reallocation allocates a larger block, moves or copies the elements and destroys the originals, invalidating every pointer, reference and iterator into the old storage. Calling reserve with an expected size prevents that churn. std::deque gives different guarantees: references survive push_back but not push_front. std::list keeps all references valid except those to erased elements.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.