带有引用参数的 C++ 函数为迭代器出错。求解释

伊利

我做了一些 C++ 评估问题,偶然发现了这个棘手的程序。

#include <deque>
#include <iostream>

using namespace std;

template<typename T>
ostream & print(T &start, T &end)
{
    for(; start != end; ++start)
    {
        cout<< *start<< " ";
    }
    return cout;
}

int main()
{
    int tab[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    deque<int> d1(tab, tab+10);
    deque<int> d2;
    deque<int>::iterator it;
    for(it = d1.begin(); it != d1.end(); ++it)
    {
        d2.push_back(d1[d1.end()-it-1]);    //LINE I
    }
    print(d2.rbegin(), d2.rend()) << endl;  //LINE II
    return 0;
}

我选择了选项程序将成功运行并显示:1 2 3 4 5 6 7 8 9 10

我后来编译了程序来测试它,它没有编译错误信息:

$g++ -o main *.cpp main.cpp: In function ‘int main()’: main.cpp:25:17: error: cannot bind non-const lvalue reference of type ‘std::reverse_iterator<std::_Deque_iterator<int, int&, int*> >&’ to an rvalue of type ‘std::deque<int>::reverse_iterator {aka std::reverse_iterator<std::_Deque_iterator<int, int&, int*> >}’   print(d2.rbegin(), d2.rend()) << endl; //LINE II
        ~~~~~~~~~^~ main.cpp:6:32: note:   initializing argument 1 of ‘std::ostream& print(T&, T&) [with T = std::reverse_iterator<std::_Deque_iterator<int, int&, int*> >; std::ostream = std::basic_ostream<char>]’  template<typename T> ostream & print(T &start, T &end)
                                ^~~~~

这个错误信息实际上是选项之一,但我认为它不会编译。

我真的不明白这是什么问题。我想如果我改变print函数的参数如下,那么它编译并成功运行:

template<typename T> ostream & print(T start, T end)
{
    for(; start != end; ++start)
    {
        cout<< *start<< " ";
    }
    return cout;
}

这是为什么?如果print函数的参数是引用,如何理解错误信息

rafix07

左值引用可以绑定到左值。如果print通过左值引用获取其参数,则在从rbegin/rend以下位置创建左值时,您的代码可以编译

auto it1 = d2.rbegin();
auto it2 = d2.rend();
print(it1,it2); // pass Lvalues

当您调用 时print(d2.rbegin(),d2.rend())按值rbegin/rend返回迭代器,因此这些迭代器是临时对象,并且由于将临时对象 (Rvalue) 绑定到 Lvalue 引用是非法的,因此您的代码无法编译。

迭代器是轻量级对象,您不需要通过引用传递它们,只需复制它们即可。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

带有括号的C ++取消引用(带有迭代器)

C ++中带有指针参数的函数

带有MATLAB语法的c ++函数参数?

Doxygen:如何引用函数,但带有参数值

带有引用参数的函数指针无法派生 Debug

没有c语警告返回对函数参数的引用

C ++未定义对具有队列参数的函数的引用

带有来自模板容器的迭代器的C ++函数

具有C ++迭代器参数的多功能函数

C:带有空指针的可变参数函数

从C调用带有字符串参数的Go函数?

c ++函数(带有主体)作为参数

带有对象指针作为参数的C ++复制构造函数

使用C ++从.dll调用带有默认参数的函数

C ++函数,带有通用参数的std :: function

在C ++中从带有参数的函数返回数组

带有可变参数的泛型函数的 C 实现

不带有任意参数的c ++函数模板

如何在c中使用带有参数的函数指针?

创建带有参数C ++的单独的类文件函数

C ++:如何在可变参数模板参数上调用带有类型参数的函数?

错误C2064:术语未求值为带有1个参数的函数-Lambda函数

C-调用带有参数且没有参数的声明的函数吗?

C++ msvc 编译器没有类型检查函数参数是一个引用

错误C2064:术语未评估为带有1个参数/使用模板的函数

是否可以将带有引用的函数作为提供自有值的闭包参数传递?

为传递引用 C++ 函数提供引用类型参数

C-将带有参数的函数传递给包装执行器

带有模板的C ++迭代器