I am writing a small game engine as a summer project, and am struggling a little with the STL map.
I have declared a class RenderList to hold objects. The RenderList will be passed to a Renderer class to do the work.
The RenderList has a map<std::string,Entity*> objects;
That all works, till I try to obtain an Entity* from the map and I get:
Assertion failed, in vc/include/xtree
Expression: map/set iterator not dereferencable.
This is the code to retrieve the pointer.
Entity* RenderList::getByName(std::string str){
return objects.find(str)->second;
}
I need it to hold a pointer and not the actual object, as there are different sub-classes of Entity which I’ll need.
I am fairly new to the STL, should I not store pointers in a map?
Surely I should be allowed to do this, or is it a better idea to store objects instead?
And finally, am I simply doing it wrong!?
Hope this question is not a duplicate, I did do a quick search beforehand. Also if this would be better in the GameDev Stack I’ll post it there.
If the key is not found then
map::find(key)returns a “past-the-end” iterator, i.e. the value returned bymap::end(), and that iterator doesn’t point to any element so can’t be dereferenced. You do not check whatfindreturns before dereferencing it.Are you sure they key is in the map?
You probably want to do something like return NULL if the key isn’t found, which you can check for by comparing the returned iterator to
ende.g.Where
RenderListdefines the typedef:(N.B. I always make my classes define typedefs for the containers I use as implementation details, because it’s much easier to write
map_type::iteratorthanmap<std::string,Entity*>::iteratorand because if I change the container to something else I don’t have to change all the code using it to e.g.map<std::string,shared_ptr<Entity>>::iteratorI can just leave it asmap_type::iteratorand it still works perfectly.)Regarding the general design, can you store a
boost::shared_ptr<Entity>orstd::tr1::shared_ptr<Entity>instead of a raw pointer? It will be much safer and simpler to manage the object lifetimes.