Consider this function to illustrate the case:
void appendAndPrint(std::vector<int> &v, int number)
{
v.push_back(number); // let there has been a reallocation
std::cout << v.back(); // does the local reference v become invalid here?
// is it safe, for example, to call here push_back() with v once again, like
// v.push_back(number);
}
and then call it with some vector:
std::vector<int> vec;
appendAndPrint(vec, 5);
Is the reference passed into the function become invalid after the first vector reallocation?
EDIT:
This construction is used quite often, but where this kind of safety is referenced in the C++ Standard?
All what is mentioned is the lifetime of references/pointers/iterators to the container elements.
Iterators and references to elements are invalidated, but not container itself. It's normal code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With