Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass C++ vector by reference and then do push_back()

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.

like image 874
trig-ger Avatar asked Mar 26 '26 07:03

trig-ger


1 Answers

Iterators and references to elements are invalidated, but not container itself. It's normal code.

like image 63
ForEveR Avatar answered Mar 27 '26 20:03

ForEveR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!