首页 > 解决方案 > 如何正确地将 const_iterator& 传递给函数?

问题描述

假设我有一个整数向量,并希望以一种奇怪的递归方式处理它(如果没有上下文,这种情况可能听起来很奇怪,但仍然如此)。

我想使用 const_iterators 来跟踪当前位置。这是odd_recursive_stuff()原型:

// Note: changing "std::vector<int>::const_iterator& it_cur"
// into "std::vector<int>::const_iterator it_cur" will change
// the side effects!
void odd_recursive_stuff (std::vector<int>::const_iterator&  it_cur, 
                          std::vector<int>::const_iterator   it_end);

首先,我尝试这样称呼它:

void process_vec (const std::vector<int> &vec) {
  odd_recursive_stuff (std::begin(vec), std::end(vec));
}

幸运的是,它没有编译(例如在 clang 8.0.0 中):

Error: no matching function for call to 'recursive_odd_stuff'
Candidate function not viable: expects an l-value for 1st argument!

因为std::begin()返回 r 值,所以我必须以另一种方式调用它:

void process_vec (const std::vector<int> &vec) {
   std::vector<int>::const_iterator it_beg = std::begin (vec);
   recursive_odd_stuff (it_beg, std::end(vec));
}

现在我想知道是否可以在recursive_odd_stuff()没有 local_variable 的情况下用单行it_beg调用 base ?

似乎不可能编写另一个begin()返回左值的版本,因为“当且仅当它是引用时,函数的返回值才是左值(C ++ 03)。(5.2.2 [ expr.call] / 10)"。所以唯一的方法是用两条线调用它?

标签: c++const-iterator

解决方案


超载!

有一个只接受右值的版本:

void odd_recursive_stuff (std::vector<int>::const_iterator&& it_cur, 
                          std::vector<int>::const_iterator   it_end);

…以及一个接受左值引用的版本(并为您做额外的行):

void odd_recursive_stuff (const std::vector<int>::const_iterator& it_cur, 
                                std::vector<int>::const_iterator  it_end)
{
    std::vector<int>::const_iterator it_copy(it_cur);
    odd_recursive_stuff(std::move(it_copy), it_end);
}

这与移动语义所基于的原则相同,因为复制和移动构造函数的选择方式相同。

但是你可能会考虑放弃这整件事,而只返回新的值it

std::vector<int>::const_iterator
odd_recursive_stuff(std::vector<int>::const_iterator it_cur, 
                    std::vector<int>::const_iterator it_end);

然后,您可以随意丢弃它。

没有人真正期望迭代器被引用。


推荐阅读