So I came across (what I think is) some wierd pointer behaviour and I was hoping someone around here might be able to explain this behaviour.
1. In the AIObject class I have a public static container that holds various AI entities, such as NPCs or monsters etc.
std::vector<AIObject*> AIObjects;
2. (In the player class I have a target)
DynamicObject* target;
3. When targeting an enemy the target is set:
this->target = AIObject::AIObjectList[activeTarget];
(There's actually a bit more in to selecting the target, but it's unrelated to this problem)
4. You are then able to do various things like casting a spell:
void Player::cast_spell(int type)
{
if (target != 0)
spells.push_back(new Spell(type, this, target));
}
Up to this point it works as I would imagine it should.
For instans, if I switch target it changes the target accordingly and if the target moves out of the screen it gets de-selected and so on.
But whenevever a target gets removed from the AIObjects vector the target member inside the Player class isn't updated accordingly.
5. In the main-loop:
if (!AIObject::AIObjects->is_alive())
{
delete AIObject::AIObjects;
AIObject::AIObjects = 0;
AIObject::AIObjects.erase(AIObject::AIObjects.begin() + i);
}
6. But in the player class:
void Player::show_active_target()
{
if (target != 0)
{
// this still gets exectued
}
}
I was under the impression that since the target pointer in the Player class is pointing to an AIObject in the AIObjects vector if the AIObject being pointed at were to get deleted so would the pointee?
I've found a work-around:
if (target != 0)
if (!target->is_alive())
target = 0;
But this isn't a very elegant solution and I would much rather understand why the target pointer isn't updated accordingly.
(For the record, Player and AIObject share the same base-class (DynamicObject) and the actual target is of type Monster which is a derrived class of AIObject.)
Thanks in advance for your help! / AS.