I have a game that has a number of ships in space. The ships exist in the gameworld as boost::shared_ptr<Ship>. These ships can attack one another. The Ship class has a boost::weak_ptr<Ship> called target, which holds a reference to whatever it's currently firing at, and it also has a vector of weak_ptr<Ship> called aggro_vector. The aggro vector records all ships that have attacked this Ship, so that when it kills its current target, it can consult its aggro vector to see which other ships it is currently in combat with, and pick a new target.
This is the Ship class, sanitised:
class Ship
{
public:
Ship (int x, int y);
boost::weak_ptr<Ship> target;
std::vector< boost::weak_ptr<Ship> > aggro_vector;
void determine_next_target();
void set_as_target (boost::shared_ptr<Ship> next_target);
}
What I'm having trouble with is getting the Ship to correctly look through its aggro_vector and choose a new target.
Here is the function that picks the next target from the aggro vector. It iterates through all the weak_ptrs, and if .lock() successfully returns a shared_ptr, it hands this shared_ptr off to the member function that registers the next target. Otherwise the weak_ptr refers to a ship that has since been destroyed and is removed from the aggro vector:
void Ship::determine_next_target()
{
std::vector< boost::weak_ptr<Ship> >::iterator it = aggro_vector.begin();
while(it != aggro_vector.end()) {
if (boost::shared_ptr<Ship> this_ship = (*it).lock()) {
set_as_target(this_ship);
++it;
} else {
it = aggro_vector.erase(it);
}
}
}
When this code is compiled and run, it crashes at the line set_as_target(this_ship). If this line is commented out, the remainder of the code works as it should (although obviously the determine_next_target() function now does nothing other than remove expired weak_ptrs).
To be clear, the set_as_target(boost::shared_ptr<Ship>) function works fine and is called from a bunch of other places in the code with no problem. It doesn't appear to be that function, but rather the fact that I'm attempting to call that function in this way.
Why am I having problems passing a shared_ptr to an outside function in this fashion? Is there something about iterating over a vector of weak_ptr that I'm missing, or am I just failing to grasp, in the broader sense, some aspect of how these pointers should be used?
Thanks in advance for any help.