Passing std algorithm iterator parameters by value vs. by reference

c++, stl, templates

Solution

One thing that comes to my mind and which is against the `const`ness in the reference: the iterators need to be modified when using them.

Another implementation detail may be that iterators are really just implemented as pointers. So are references in most cases. If you pass the pointer by value, you copy it once but dereference it only when needed. If, however, the iterator-pointer itself is passed by a reference-pointer, then that has to be dereferenced first, just in order to get to the iterator, and that must be done each time the iterator is accessed. That is superfluous.

Problem

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!

Original source

Related problems