Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a vector cause error but standard for-loop does not

I have a vector that holds pointers to abstract type Rock:

vector<Rock*> rocks;

If I loop through the vector with an iterator and then try to access the object (a non-abstract class that extends Rock) via the iterator, I get an 'EXC_BAD_ACCESS' error in XCode 4:

vector<Rock*>::iterator rockIter;
for (rockIter = rocks.begin(); rockIter != rocks.end(); ++rockIter)
{
  bullet.hit(*(*rockIter));
}

But looping through it normally like is no problem:

for (int i = 0; i < rocks.size(); i++)
{
  bullet.hit(*rocks[i]);
}

The function hit() looks like:

bool Bullet::hit(Rock & rock)

I thought that *(*rockIter) and *rock[i] would do the same thing but clearly they dont. What is different, and how can I pass a reference of an object in the vector via an iterator like I do with *rock[i]?

like image 747
Austin Moore Avatar asked Mar 30 '12 01:03

Austin Moore


1 Answers

Without seeing more code I'm not sure if this is the problem, but is the code in bullet.hit() changing the vector by adding elements? If it is and you're iterating over it using an iterator, that iterator will get invalidated and any future dereferences on it will result in undefined behavior. However, using the standard int-based for loop will not have this problem, because accesses by index can't be invalidated.

Hope this helps!

like image 57
templatetypedef Avatar answered Nov 02 '22 07:11

templatetypedef