按值与按引用传递 std 算法迭代器参数 [英] Passing std algorithm iterator parameters by value vs. by reference

查看:30
本文介绍了按值与按引用传递 std 算法迭代器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在 STL 中的许多模板算法中,参数不是通过引用传递而是通过值传递.以下是 > 标头中的示例:

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 <iterator> header:

template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);

当我向这个函数传递两个迭代器时,它们被复制.我天真的想法是最好通过常量引用传递这些迭代器以避免复制迭代器对象:

When I pass two iterators to this function, they are copied. My naive thoughts are that it would be better to pass these iterators by const-reference to avoid copying the iterator objects:

template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (const InputIterator &first, const InputIterator &last);

可以说迭代器通常是非常小的对象,复制它们并不昂贵.但即便如此:廉价的复制会比根本不复制更昂贵.

One could say that iterators are in general very small objects and that copying them is not expensive. But even still: cheap copying would be more expensive than no copying at all.

那么在 STL 版本中,迭代器是按值传递的原因是什么?

So what is the reason that in the STL-version, the iterators are passed by value?

谢谢!

推荐答案

我想到的一件事与参考中的 constness 背道而驰:迭代器在使用时需要修改

One thing that comes to my mind and which is against the constness in the reference: the iterators need to be modified when using them.

另一个实现细节可能是迭代器实际上只是作为指针实现的.在大多数情况下,引用也是如此.如果按值传递指针,则复制一次,但仅在需要时取消引用它. 但是,如果迭代器指针本身是通过引用指针传递的,则那个 必须首先取消引用,以便访问迭代器,并且每次访问迭代器时都必须这样做.那是多余的.

Another implementation detail may be that iterators are really just implemented as pointers. So are references in most cases. If you pass the pointer by value, you copy it once but dereference it only when needed. If, however, the iterator-pointer itself is passed by a reference-pointer, then that has to be dereferenced first, just in order to get to the iterator, and that must be done each time the iterator is accessed. That is superfluous.

这篇关于按值与按引用传递 std 算法迭代器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆