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]
?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With