In this context, I think that passing an iterator by reference is perfectly sensible, as long as it's well-documented. It's worth noting that your approach (passing an iterator by reference to keep track of where you are when tokenizing a stream) is exactly the approach that is taken by boost::tokenizer.
Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++().
I'm wondering why in many template algorithms in the STL the arguments are not passed by reference but rather by value. Here is an example from the <iterator
> header:
template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);
When I pass two iterators to this function, they are copied. My naive thoughts are that it would be better to pass these iterators by const-reference to avoid copying the iterator objects:
template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (const InputIterator &first, const InputIterator &last);
One could say that iterators are in general very small objects and that copying them is not expensive. But even still: cheap copying would be more expensive than no copying at all.
So what is the reason that in the STL-version, the iterators are passed by value?
Thank you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With