Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return an iterator or a pointer to an element in a STL container?

Tags:

c++

stl

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?

like image 508
BeeBand Avatar asked Sep 13 '10 11:09

BeeBand


2 Answers

Both an iterators or a pointers will do bad stuff if you try to access them after the object has been deleted so neither is intrinsically safer. The advantage of an iterator is that it can be used to access other members of your collection.

So, if you just want to access your Shape then a pointer will be simplest. If you want to iterate through your list then use an iterator.

An index is useless in a list since std::list does not overload the [] operator.

like image 124
doron Avatar answered Oct 17 '22 01:10

doron


The answer depends on your representation:

  • for std::list, use an iterator (not a pointer), because an iterator allows you to remove the element without walking the whole list.
  • for std::map or boost::unordered_map, use the Key (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 map and unordered_map to see which one is faster in your case :)

like image 34
Matthieu M. Avatar answered Oct 17 '22 02:10

Matthieu M.