[gdal-dev] Use of C++ iterators in API
Alex HighViz
alexhighviz at hotmail.com
Thu Apr 12 10:45:57 PDT 2018
> Even:
> In fact the nature of the object which is returned depends on the iterator, and as documented in the API, for the sake of implementation simplicity, those iterators do not necessarily respect the whole semantics of iterators.
I don't think that is necessary, at least in the case of Layers you can conform to the InputIterator concept without much extra work
[snip]
> So basically you should only use them in range based loops, where you don't really manipulate the iterator and cannot do stuff like the above.
That is also the limitation of InputIterator.
> Improvements (if doable and not adding (too much) overhead to the underlying objects) are welcome of course.
I would recommend that Layers::iterator is updated to conform to the C++ iterator concepts (to the very least to the InputIterator concept).
It still requires the following:
- five typedefs (value_type, reference, pointer, iterator_category, difference_type)
- three constructors (default, copy, move)
- two assignment operators (copy, move)
- post-increment operator (operator++(int))
See also http://en.cppreference.com/w/cpp/concept/InputIterator.
*************************************************
Regarding the for(auto&& layer : layers) discussion:
The return type of Layers::Iterator::operator*() is OGRLayer*.
Therefore, the following:
for(auto& layer : layers)
is incorrect and should not compile, because it binds a temporary to a reference.
Furthermore, the following:
for(const auto& layer: layers)
is only correct because an assignment of a temporary to a const reference extends its lifetime, and it is therefore equivalent to
for(const auto layer : layers)
Considering the potential confusion, you can just avoid the issue completely and write:
for(const OGRLayer* layer : layers)
Kind regards, Alex
More information about the gdal-dev
mailing list