Passing std algorithm iterator parameters by value vs. by reference

前端 未结 4 2002
逝去的感伤
逝去的感伤 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:49

    For certain cheap-to-copy types, passing them by value is actually faster than passing by reference. Conventional wisdom from tutorials, etc., states that by reference is faster, but this does not necessarily apply to cheap-to-copy types.

    How do you pass an object by value? You make a copy of it, which means you take the value and push it to the stack for the function call. And how do you pass by reference? You push the memory address to the stack, and then the called function has to fetch whatever is at that address. Now, optimization and caching may come into play to make that memory fetch much cheaper, but you still don't get cheaper than taking the exact value from the stack. Which in the case of iterators is often something as simple as a mere pointer. Which is one word long and so very cheap to copy.

    Also, note you're suggesting to pass a const reference. Which means it would have to be copied anyway in the called function to let it be modified (such as incrementing in a loop).

提交回复
热议问题