Why isn't first
passed as a reference and const as well?
template <typename Iterator>
int distance(Iterator first, const Iterator & last) {
int count;
for ( ; first != last; first++)
count++;
return count;
}
The const keyword in front of the object name is used to guarantee that your function does not modify the objects that are passed to the function by reference or pointer. Not only will this tell other programmers that your function is safe to use, it is also strictly enforced by the compiler.
Although you must recompile any code that calls the function, you need not rewrite the calls. In short, passing by reference-to-const is a potentially efficient alternative to passing by value. To the calling function, an argument passed by reference-to-const looks and acts just like one passed by value.
Passing By Reference To Const in C++ | QuantStart. Passing By Reference To Const in C++ Passing By Reference To Const in C++ C++ is an example of a message-passing paradigm language, which means that objects and values are passed to functions, which then return further objects and values based on the input data.
Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument.
It cannot be const
because it is incremented inside the function, and it is not passed by reference because it probably makes no sense to do so for the caller.
Furthermore, if it were non-const reference, it would not be possible to use a temporary. For example, you wouldn't be able to do tis:
std::vector<int> v{ 1, 2, 3, 4 };
auto distance = std::distance(v.begin(), v.end());
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