[geos-devel] Problem with returning Coordinate* from CoordinateList accessor

Martin Davis mbdavis at VividSolutions.com
Fri Nov 15 12:55:40 EST 2002


Dave says:

> Yes - I like that. The getAt(int) should return a non-pointer 
> or its should allocate a new Cooridinate and return that.

I've just realized a big problem with our current thoughts about how CoordinateLists return Coordinates.  We've been assuming that CoordinateList has a Coordinate* getAt(int i) method. The problem with this is that if the CoordinateList implementation is build on some structure which doesn't contain Coordinates (e.g. like POINT2D or something), we'd end up having to allocate a new Coordinate each time (and the caller would have to free it).  This would result in lots of needless malloc traffic, as well as being a likely source of memory bugs.  

I think this means that the only safe, general way of accessing Coordinates in a CoordinateList is by value.  Currently we have:

Coordinate CoordinateList::getAt(int i)

This probably results in all kinds of constructor calls, however.  To avoid this, we can provide a method:

void CoordinateList::getAt(int i, Coordinate& coord)  // calls coord.setX and setY directly

The caller would provide the Coordinate object to receive the value.  This lets the caller decide how it wants to manage memory.  In fact, in many cases in JTS, the caller can simply allocate a single Coordinate on the stack to receive the values of each coord as it iterates over a CoordinateList.

The by-value approach has another advantage as well - it provides complete encapsulation of the data inside the CoordinateList, thus providing us with a way to implement non-mutability, if needed. In fact, this is exactly the scheme I've been thinking of implementing in JTS, to support non-mutability.

The only other option I can see is to use some cheesy casting scheme inside CoordinateList, relying on the underlying implementation storing the ordinate values for each point in contiguous memory.  Yuck!


Martin Davis, Senior Technical Specialist
Vivid Solutions Inc.
Suite #1A-2328 Government Street   Victoria, B.C.   V8T 5G5
Phone: (250) 385 6040    Fax: (250) 385 6046
EMail: mbdavis at vividsolutions.com  Web: www.vividsolutions.com





More information about the geos-devel mailing list