Re: Don't know why it is
"Jacky" <jl@knight.com> schrieb im Newsbeitrag
news:eyUcV5mUHHA.4632@TK2MSFTNGP04.phx.gbl...
Hi,
I'm reading a book on STL
I wonder why I is by value while T is by reference.
template <class I, class T>
I find (I first, I last, const T& value)
{
while (first != last && *first != value)
++first;
return first;
}
Thanks a lot
Jack
Notice that first is modified inside the function. Now consider what would
happen if first is passed by value, const reference or non-const reference.
If it were passed by non-const reference, any changes to first made inside
the function would be visible to the called. Also, you must pass an l-value
when a non-const reference is expected as a parameter. So you wouldn't be
able to write simple code like
find(data.begin(), data.end(), value);
Now if a const reference would be used, there wouldn't be a local copy of
first, and the function would have to make one itself. So you don't save
anything if you pass first by const reference, but there might be situations
where the compiler has to create a temporary object to bind the reference
to, and the first thing the function will do, is making another copy of that
temporary.
If first, however, is passed by value, the function can directly use and
modify that copy of the input value. So passing first by value is the best
choice. last could be passed by const reference, but then you would probably
ask why first is passed by value and last by const reference. And if, for
whatever reason, the function would have to modify last as well, the whole
discussin would start all over.
Finally, I is an interator, a relativly small object, so there wouldn't be
much gain if it were passed by reference. Als, the little overhead for
passing such small objects by value is negectable for a function which might
have to compare millions of large objects to find the one you are looking
for.
HTH
Heinz