Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the second variable passed as a reference and const

Tags:

c++

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;
}
like image 915
code511788465541441 Avatar asked Aug 14 '12 14:08

code511788465541441


People also ask

Why would we put the const keyword in front of a pass by reference parameter?

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.

Can a const be passed by reference?

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.

What does pass by const reference mean?

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.

Why is it better to pass by reference?

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.


1 Answers

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());
like image 132
juanchopanza Avatar answered Sep 26 '22 12:09

juanchopanza