Would someone please take a look at the following code fragments (all from one file) and advise on the problem I will describe at the end?
members:
std::vector<cHasAMyClass> collected;
std::vector<cHasACHasAMyClass> memberVector;//Actually an array of vectors, but simpler not to be.
constructor of an inner/local class:
cHasACHasAMyClass(cHasAMyClass *ptrToCHasAMyC, int stuff) :
masterRef(ptrToCHasAMyC),
other_stuff(stuff) {}
method I was using:
cHasAMyClass *firstUniqueOccurrence(std::vector<cHasAMyClass> *masterList, myClass *qSq) {
for (int i = 0; i < (int)masterList->size(); ++i)
if ((*masterList)[i].myClassPtr == qSq) return &((*masterList)[i]);
masterList->push_back(cHasAMyClass(qSq));
return &(masterList->back());
}
block which calls above method:
{
std::vector<myClass *> allAtLoc;
if (map->getAllHere(curLoc, &allAtLoc)) {
for (int i = 0; i < (int)allAtLoc.size(); ++i) {
int stuff = 42; //Or otherwise
cHasAMyClass *newContainer = firstUniqueOccurrence(&(collected), allAtLoc[i]);
memberVector.push_back(cHasACHasAMyClass(newContainer, stuff));
}
}
allAtLoc.clear();
}
Problem is sometime later (ok prolly immediately on leaving the above block) memberVector[0].masterRef appears messed up which I detect (apart from crashing) because its member of type myClass is invalid or null. I thought I had set it to a pointer to persisting object (managed in another data structure, a simple array (/ptr – it’s new/malloc‘d)) but I’m new to using vectors and not sure what sort of indirection I was witnessing.
I have allAtLoc and newContainer going out of scope and though they are but pointers to objects, they have side effects. Incidentally, my collected vector doesn’t contain errors.
This was all working fine before I made the move to std::vectors, I don’t understand how my indirection is wrong, please could someone advise?
It’s hard to read your code, but it looks like you are taking pointers to elements within a
vector. Pointers, iterators and references to avectorare invalidated when its capacity changes. That can happen as a side effect of any function that inserts into thevector, since a new bigger internal array is created into which the current contents are copyed.If you want to use pointers to elements in a
vector, you have to make sure they won’t be invalidated. If you know the number of elements, you could callreserveprior to inserting any elements.