1

As I understand it, as long I do not delete or add items to vector, the items memory location does not change, so I can create a reference to some elements in the vector without worrying they will not be valid.

Is it safe to use refToVec, as long I do not delete/add items to vec??

vector<int> vec;
for (int i = 0; i < 10; i++)
    vec.push_back(i);

vector<reference_wrapper<int>> refToVec;
for (auto &item : vec)
{
    if (item % 2)
        refToVec.push_back(item);
}

//is it safe to use refToVec?
for (auto &item : refToVec)
    item += 100;

I am using VS 2013

Community
  • 1
  • 1
user1438233
  • 1,153
  • 1
  • 14
  • 30

1 Answers1

2

Yes, it's safe. As long as you don't add elements to a vector (beyond what has been reserve'd), pointers, references and iterators will stay valid.

jalf
  • 243,077
  • 51
  • 345
  • 550