Passing std algorithm iterator parameters by value vs. by reference

前端 未结 4 2000
逝去的感伤
逝去的感伤 2021-02-19 04:45

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 > h

4条回答
  •  不知归路
    2021-02-19 04:50

    The concept of std iterators is the generalisation of a pointer. The iterators of the std containers are commonly implemented as a type that composes a single pointer. In the case of an argument type that is as cheap to copy as a pointer, passing the argument by reference is more expensive than passing it by value. A reference to an object must be dereferenced before the object's value can be used. See this answer for more details.

    Because almost all std algorithms need to make copies of iterators, in order to obtain the best performance it's already essential that an iterator is cheap to copy. For this reason, it's very unusual to find an iterator which is significantly more expensive to pass by value than by reference.

    In the case of std::distance - and many other algorithms - the entire algorithm is so simple that the call will very likely be inlined by the compiler. If the call is inlined, it does not matter whether the argument passed by reference or by value. [Note that an inlined function call is not the same as an inline function declaration!]

    In the case of an iterator being more expensive to pass by value than by reference, and the function call not being inlined, you could make an argument for passing iterators by rvalue-reference. The performance gain in such a rare case is probably not worth the additional complexity.

提交回复
热议问题