I am creating a Tower Defence game mockup where enemies attempt to cross the screen before they are destroyed.
Pointers to dynamically allocated Enemy objects are stored in a vector inside an EnemyManager class that controls how they spawn and despawn. When the health of an Enemy reaches zero the EnemyManager deletes it using delete
, and also erase
s the pointer.
I have a BulletTower object that is meant to lock on to a single Enemy and shoot until it is destroyed, then lock onto another. This requires a pointer to an Enemy object, but if the Enemy dies and is deleted by the EnemyManager, the pointer is dangling.
There doesn't seem to be a way the pointer can tell if the enemy being locked on to is destroyed. I looked into smart pointers, but it seems like shared pointers wouldn't work given that the enemies are being manually deleted when their health reaches zero.
Weak pointer could perhaps do the job.
Also, instead of giving a Enemy pointer to BulletTower, you could give a function or object which would return the current locked enemy if alive, or return a new one.