My game uses an entity manager and entities to represent everything including the player, enemes, items, ..everything in the game. In my engine it's the responsibility of every entity to update itself.
Sometimes an entity finds out it has expired somehow, and thus needs to remove itself from the entity manager. My question is: Is it safe to have an object delete itself? I will illustrate what I mean.
void EntityManager::remove_entity(Entity* entity) {
m_entities.erase(std::remove_if( //...
}
void Entity::update() {
if (has_expired)
m_manager.remove_entity(this); // <- safe?
}
I can't concretely prove a bug by using this, but it kind of looks and feels like it should at least be undefined behaviour. So is it OK? If not, what is a common practice for dealing with this situation?
m_entities
? IsEntity::update
called while iterating overm_entities
? \$\endgroup\$std::shared_ptr<Entity>
. Yes, it is call when iteratingm_entities
. \$\endgroup\$