dimanche 19 avril 2015

Is reference to elements in std::vector safe

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


Aucun commentaire:

Enregistrer un commentaire