Why is the second variable passed as reference and const

Why is not the first passed as reference and const?

 template <typename Iterator> int distance(Iterator first, const Iterator & last) { int count; for ( ; first != last; first++) count++; return count; } 
+7
source share
4 answers

It cannot be const , because it grows inside the function and is not passed by reference, because there is probably no point in doing this for the caller.

Also, if it were a non-constant reference, it would be impossible to use a temporary one. For example, you cannot make tis:

 std::vector<int> v{ 1, 2, 3, 4 }; auto distance = std::distance(v.begin(), v.end()); 
+7
source

Because it is changed inside a function, therefore it cannot be const. However, you do not want its state (its value) to change outside the function, so it was passed by value (without reference).

+6
source

The best question is why the second argument is passed by the const reference, since the signature defined in the standard is this:

 template <typename Iterator> typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last); 

That is, as in meaning.

+4
source

Because if we do not want to change the value of the caller, we still need to create a copy.

+1
source

All Articles