Every time I consider making my code strongly exception safe, I justify not doing it because it would be so time consuming. Consider this relatively simple snippet:
Level::Entity* entity = new Level::Entity(); entity->id = GetNextId(); entity->AddComponent(new Component::Position(x, y)); entity->AddComponent(new Component::Movement()); entity->AddComponent(new Component::Render()); allEntities.push_back(entity); // std::vector entityById[entity->id] = entity; // std::map return entity;
To implement a basic exception guarantee, I could use a scoped pointer on the
new calls. This would prevent memory leaks if any of the calls were to throw an exception.
However, let's say I want to implement a strong exception guarantee. At the least, I would need to implement a shared pointer for my containers (I'm not using Boost), a nothrow
Entity::Swap for adding the components atomically, and some sort of idiom for atomically adding to both the
Map. Not only would these be time consuming to implement, but they would be expensive since it involves a lot more copying than the exception unsafe solution.
Ultimately, it feels to me like that time spent doing all of that wouldn't be justified just so that the a simple
CreateEntity function is strongly exception safe. I probably just want the game to display an error and close at that point anyway.
How far do you take this in your own game projects? Is it generally acceptable to write exception unsafe code for a program that can just crash when there is an exception?