I am developing an engine for porting existing code to a different platform. The existing code has been developed using a third party API, and my engine will redefine those third party API functions in terms of my new platform.
The following definitions come from the API:
typedef unsigned long shape_handle;
shape_handle make_new_shape( int type );
I need to redefine make_new_shape and I have the option to redefine shape_handle.
I have defined this structure ( simplified ):
struct Shape
{
int type
};
The Caller of make_new_shape doesn’t care about the underlying structure of Shape, it just needs a “handle” to it so that it can call functions like:
void `set_shape_color( myshape, RED );`
where myshape is the handle to the shape.
My engine will manage the memory for the Shape objects and other requirements dictate that the engine should be storing Shape objects in a list or other iterable container.
My question is, what is the safest way to represent this handle – if the Shape itself is going to be stored in a std::list – an iterator, a pointer, an index?
The answer depends on your representation:
std::list, use aniterator(not a pointer), because aniteratorallows you to remove the element without walking the whole list.std::maporboost::unordered_map, use theKey(of course)Your design would be much strong if you used an associative container, because associative containers give you the ability to query for the presence of the object, rather than invoking Undefined Behavior.
Try benchmarking both
mapandunordered_mapto see which one is faster in your case 🙂