I have to create an iterator for an API that features old-style "write-out to pointer" accessors only. The API in question is OGR's; one of the classes in question is OGRLineString
(For reference: Link). This class stores a number of points, which can be accessed using the following getter method:
void OGRLineString::getPoint(int pos, OGRPoint *out)
In order to use the accessor one creates a new OGRPoint
object and passes the pointer to it to the method, which writes the data to the allocated object. For example:
OGRPoint *p = new OGRPoint();
lineString->getPoint(0, p);
Now, I'd like to implement a (STL-like) iterator. Even if I place big warning signs everywhere stating that the supplied OGRPoint
s are non-modifiable (i.e., const
), and won't update if another piece of code modifies the OGRLineString
that is being iterated, I get a memory leak problem with OGRPoint const &operator*() const
, because the API requires me to pass a custom-allocated OGRPoint
instance, but the iterator would have to allocate one. Plus, the OGRPoint
s returned by the iterator shouldn't be deleted when the iterator itself is deleted. Additionally, the OGRLineString
does not store actual instances of OGRPoint
that are being copied for getPoint
, but simple structs storing x/y/z coordinates; all required additional information (e.g., the spatial reference) is copied in the accessor. Thus, a simple #define private public
hack wouldn't help.
Is there any sane/clean way to add an iterator without modifying the original source of OGRLineString
? E.g., is there a way to add features to the original class, or modify it, like Ruby's "monkey patching" feature would do? Or watch the container's life time in order to clean up on the OGRPoint
instances returned by the iterator?